简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM