This article demonstrates how to format a number to two decimal places in PHP.

1. Using number_format() function

You can use the number_format() function to format a number to the desired number of digits after the decimal point. It takes four parameters: the number being formatted, the number of decimal digits to set, the decimal separator, and the thousands’ separator, in that order. This works, but it returns a formatted string and not a number. If you need the float value instead of a string, you can pass the returned string to the floatval() function.

Download  Run Code

2. Using sprintf() function

Alternatively, you can use the sprintf() function to format a number. It produces a string according to the specified formatting string. You can format a number to two decimal places using the %.2f modifier. The following code example demonstrates:

Download  Run Code

3. Using round() function

If you need to round the value to a given precision after the decimal point, you can use the round() function. The following sample illustrates its usage. Note that the round() function does not add trailing zeros to the number, to match the required digits after the decimal point.

Download  Run Code

 
The default rounding mode of round() is PHP_ROUND_HALF_UP which rounds the number away from zero when it is half way there. There are several other constants that indicate the mode in which rounding occurs. These modes are PHP_ROUND_HALF_DOWN, PHP_ROUND_HALF_EVEN, and PHP_ROUND_HALF_ODD, which round the specified number towards zero, the nearest even value, and the nearest odd value, respectively.

4. Using bcadd() function

Finally, you can leverage the BC math function bcadd(), which can add its two operands according to the specified scale, indicating the number of digits after the decimal place in the result. To format a number to two decimal places, you can use that number as the first operand and 0 as the second operand and provide a scale of 2. The following code demonstrates:

Download  Run Code

That’s all about formatting a number to two decimal places in PHP.