Skip to content
Advertisement

Remove useless zero digits from decimals and remove decimals above 2 in PHP

I’m trying to find a fast way to first make my number 2 decimals only and then remove zero decimals from result values like this:

echo function(0.00);
// 0

echo function(125.70);
// 125.7

echo function(245.051);
// 245.05

echo function(2245.0090);
// 2245.01

I tried number format but when I call it with 0 it acts like this:

echo number_format(0,2)
// 0.00

But I want 0

Does there exist some optimized way to do that?

Advertisement

Answer

There are probably better ways to achieve this, but the first approach that springs to mind is simply trimming it away using rtrim() with .0 as the trim. This will however also trim entirely away when you have cases like 0.00 (and just return an empty string), so we can perform an explicit check for that.

function myFormat($number, $precision = 2) {
    $number = rtrim(round($number, $precision), '.0');
    if (empty($number)) {
        $number = 0;
    }
    return $number;
}

echo myFormat(0.00); // 0
echo myFormat(0.01); // 0.01
echo myFormat(0.10); // 0.1
echo myFormat(1.00); // 1
echo myFormat(2245.0090); // 2245.01
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement