Borsn Borsn - 2 months ago 14
PHP Question

Round floats decimals to nearest tenth in PHP

After converting currencies, I get a float that would look something like

2.68
.

Tried rounding up with
ceil($input / 10) * 10
but that doesn't work for floats.

So is there a simpler way for rounding floats to the nearest tenth?
I'd like to get
2.70
.




The more complicated way for me to do this would be to
explode
the float at the
.
then round
68
with
ceil
. And then combine them.

But what If the number is
2.96
. It will need to be
3.00
rounded, so this makes it really complicated.

Answer

You simply got the math wrong, it should be multipled-then-divided, not the other way around:

ceil($input * 10) / 10

But that only rounds up. Rounding in each direction works with round...

round($input * 10) / 10

But wait, round has a second param, just for this! :)

round($input, 1) // round with precision of 1 digits after the decimal point