How to keep two decimal places in PHP.

Question

Answers ( 1 )

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

    In PHP, there are several methods to keep or format a number to two decimal places. Here are some common methods:

    1. Using number_format() Function: The number_format() function formats a number with grouped thousands and a specified number of decimal places. If you only want to keep two decimal places, you can use it like this:

      $number = 123.456;
      $formattedNumber = number_format($number, 2);
      echo $formattedNumber; // Outputs: 123.46
      

      This will round the number to two decimal places.

    2. Using round() Function: The round() function rounds a floating-point number. To round to two decimal places:

      $number = 123.456;
      $roundedNumber = round($number, 2);
      echo $roundedNumber; // Outputs: 123.46
      
    3. Using sprintf() or printf() Functions: These functions are used for formatted output. To format a number to two decimal places:

      $number = 123.456;
      echo sprintf("%.2f", $number); // Outputs: 123.46
      

      Or, if you want to directly output it:

      printf("%.2f", $number); // Outputs: 123.46
      
    4. Using bcadd() Function (For Arbitrary Precision): If you are dealing with very large numbers or need high precision, you might want to use the bcadd() function. Note that this requires the BC Math extension to be enabled in PHP.

      $number = '123.456';
      $roundedNumber = bcadd($number, '0', 2);
      echo $roundedNumber; // Outputs: 123.46
      

    Each of these methods has its own use case. number_format() is useful for formatting numbers for display, round() for general rounding, sprintf()/printf() for formatted strings, and bcadd() for high precision arithmetic.

Leave an answer