Skip to content
Advertisement

Remove trailing zeros until 2 decimals in PHP

I’ve tried casting to float and number_format but float will always round at two and number_format is fixed on the amount of decimals you specify.

So how can I do this like the following conversion

11.2200 -> 11.22
11.2000 -> 11.20
11.2340 -> 11.234

Advertisement

Answer

You can use float casting

echo (float) 11.2200;
echo "<br/>";
echo (float) 11.2000;
echo "<br/>";
echo (float) 11.2340;

and you have to check number of digits after decimal point and than get value like below :

$val=(float) 11.2000;
if(strlen(substr(strrchr($val, "."), 1))<2){
    echo number_format($val,2);
} 
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement