Search code examples
phpnumbersdecimal

Remove useless zero digits from decimals in PHP


I'm trying to find a fast way to remove zero decimals from number values like this:

echo cleanNumber('125.00');
// 125

echo cleanNumber('966.70');
// 966.7

echo cleanNumber(844.011);
// 844.011

Does exists some optimized way to do that?


Solution

  • $num + 0 does the trick.

    echo 125.00 + 0; // 125
    echo '125.00' + 0; // 125
    echo 966.70 + 0; // 966.7
    

    Internally, this is equivalent to casting to float with (float)$num or floatval($num) but I find it simpler.