Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

php

rounding

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?

like image 250
Tiny Avatar asked Oct 20 '12 14:10

Tiny


People also ask

How do you round up decimals in PHP?

The round() function rounds a floating-point number. Tip: To round a number UP to the nearest integer, look at the ceil() function. Tip: To round a number DOWN to the nearest integer, look at the floor() function.

How do you round to 2 decimal places in PHP?

Example #1 round() examples php echo round(3.4); // 3 echo round(3.5); // 4 echo round(3.6); // 4 echo round(3.6, 0); // 4 echo round(1.95583, 2); // 1.96 echo round(1241757, -3); // 1242000 echo round(5.045, 2); // 5.05 echo round(5.055, 2); // 5.06 ?>

Does .2f round?

2f and see what happens. As expected, the floating point number (1.9876) was rounded up to two decimal places – 1.99. So %. 2f means to round up to two decimal places.


1 Answers

number_format(123.455, 2, '.', '')
like image 92
AndreKR Avatar answered Sep 30 '22 12:09

AndreKR