PHP: Get two decimal places,

Question

Answers ( 1 )

    0
    2024-01-11T18:05:20+00:00

    This question is about formatting numbers in PHP to show only two decimal places.

    There are multiple ways to achieve this in PHP:

    1. Using round() Function

    The round() function in PHP is used to round a float to a specified number of decimal places.

    $number = 123.456;
    $roundedNumber = round($number, 2); // Rounds to 123.46
    

    2. Using number_format() Function

    The number_format() function is used for formatting a number with grouped thousands and a specified number of decimal points. This function also rounds the number.

    $number = 123.456;
    $formattedNumber = number_format($number, 2); // Formats and rounds to 123.46
    

    3. Using sprintf() or printf()

    These functions are used for string formatting and can also format numbers. sprintf() returns the formatted string, while printf() displays it.

    $number = 123.456;
    $formattedNumber = sprintf('%.2f', $number); // Formats to 123.46
    

    4. Using floor() or ceil() with Multiplication and Division

    If you need to truncate without rounding, you can multiply the number, use floor() or ceil(), and then divide it back.

    $number = 123.456;
    $truncatedNumber = floor($number * 100) / 100; // Truncates to 123.45 without rounding
    

    Each of these methods has its own use case depending on whether you want to round the number or maintain its original value, and how you want to handle the number formatting.

Leave an answer