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?
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.
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 ?>
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.
number_format(123.455, 2, '.', '')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With