phpfloating-pointnumbersdecimalnumber-formatting

number_format() php remove trailing zeros


Is there a way with number_format() to leave out decimal places if the number is not a float/decimal?

For example, I would like the following input/output combos:

50.8 => 50.8
50.23 => 50.23
50.0 => 50
50.00 => 50
50 => 50

Is there a way to do this with just a standard number_format()?


Solution

  • You can add 0 to the formatted string. It will remove trailing zeros.

    echo number_format(3.0, 1, ".", "") + 0; // 3
    

    A Better Solution: The above solution fails to work for specific locales. So in that case, you can just type cast the number to float data type. Note: You might loose precision after type casting to float, bigger the number, more the chances of truncating the number.

    echo (float) 3.0; // 3
    

    Ultimate Solution: The only safe way is to use regex:

    echo preg_replace("/\.?0+$/", "", 3.0); // 3
    echo preg_replace("/\d+\.?\d*(\.?0+)/", "", 3.0); // 3
    

    Snippet 1 DEMO

    Snippet 2 DEMO

    Snippet 3 DEMO