Alexander Lomia Alexander Lomia - 1 month ago 7
PHP Question

Show only one decimal place or nothing of a floating point number

I'm aware of

number_format(..)
that behaves like following:

number_format(2.5, 1) // returns 2.5
number_format(2.0, 1) // returns 2.0 <-- needs to be just 2


The problem is, that I don't want
.0
to be shown at all. How to format the float correctly to achieve this?

Answer

One option is to use round instead of number_format:

echo round(2.0, 1); // 2
echo round(2.5, 1); // 2.5
echo round(2.555555, 1); // 2.6
echo round(2.501, 1); // 2.5
echo round(2.1050, 1); // 2.1

Another option is to cast your number to a float after using number_format, which will eliminate any trailing zeros after the decimal point.

echo (float) number_format(2.0, 1); // 2
echo (float) number_format(2.5, 1); // 2.5
echo (float) number_format(2.555555, 1); // 2.6
echo (float) number_format(2.501, 1); // 2.5
echo (float) number_format(2.1050, 1); // 2.1

Both will give you a maximum of a single decimal place. I think round is the better option here.

Comments