Search code examples
phprounding

Always display specified number of decimal places in PHP (rounding up)


I need to display a floating point number with a specified number of decimal places (rounding up), specifically up to two decimal places even though the number has no fractional part. One way that I know is by using the sprintf() PHP function as follows.

echo sprintf("%0.2f", 123);

It returns 123.00.

echo sprintf("%0.2f", 123.4555);

returns 123.46 but the following doesn't return what I need.

echo sprintf("%0.2f", 123.455);  // 5 is removed - the right-most digit.

I expect it to return 123.46 but it doesn't. It returns 123.45. Although it's not a huge difference, I somehow need to return 123.46 in both of the cases.


The round() function can do it. echo round(123.455, 2); and echo round(123.4555, 2); return 123.46 in both the cases but I can't think of using this function because if the fractional part is not present, it displays no decimal digits at all. like echo round(123, 2); gives 123 and I need 123.00.

Is there a function in PHP to achieve this?


Solution

  • number_format(123.455, 2, '.', '')