Borsn Borsn - 1 year ago 55
PHP Question

Round floats decimals to nearest tenth in PHP

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


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

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

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

Answer Source

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