An efficient way to remove extraneous zeros from prices?

I have prices stored to five decimal places of precision, for example:

1.95000
2.25000
0.01150
2.10000
2.00000

      

When you show prices, I would like to show the standard format $X.XX

if the rest of the digits are zero, but if there are significant digits, I don't want to strip them out (so I can't just use it number_format()

).

As an example, the above prices should be displayed as:

1.95
2.25
0.0115
2.10
2.00

      

This process has to be done with hundreds of prices per page. What's an efficient way to format numbers this way?

+3


source to share


2 answers


It's disgusting, but it does the job:

function formatPrice($price) {
    $out = (float)$price; // Trim off right-hand 0's
    $out = "$out"; // Typecast back to string
    if ((strlen($out) - strpos($out, '.')) <= 2) { // Test for string length after decimal point
        $out = number_format($out, 2); // Format back with 0's
    }
    return $out;
}

      

Testing now ... It works!



Here's a one-line function from my other comment thanks to @FuzzyTree's answer:

function formatPrice($price) {
    return substr($price, 0, strpos($price, '.') + 3) . rtrim(substr($price, strpos($price, '.') + 3), '0');
}

      

+2


source


In this case, a regex is used to match all values ​​up to the end of 0s

$i = "$1.00";
$pattern = '/\$(\d+)\.(\d\d)(0*)/';
$replacement = '\$$1.$2';
print preg_replace($pattern,$replacement,$i);

      



Another use rtrim

for everything after the first two digits to the right of the decimal

$pos = strpos($i, '.') + 3;
print substr($i, 0, $pos) . rtrim(substr($i, $pos), '0');

      

+3


source







All Articles