Log in

View Full Version : Need to remove trailing .00 from a price



qwikad.com
09-03-2014, 02:10 AM
This is what I am using:


<?php
$price = $ad['price'];
echo number_format($price, 2, '.', ',');
?>

Prices are displayed like this: 1,500,000.00 or 1,125.00 or 1.00

I want them to show like this: 1,500,000 or 1,125 or 1

However I still want to show decimals in prices that are 1.09 or 110.75 or 1,111.99 or whatever.

I just want to get rid of the decimal zeros.

Thanks!

keyboard
09-03-2014, 03:45 AM
+0 to the value

<?php
$price = $ad['price'] + 0;
echo number_format($price, 2, '.', ',');
?>

If that doesn't work use



<?php
$price = (float)$ad['price'];
echo number_format($price, 2, '.', ',');
?>


to cast it from a string to a float

Don't mind me :p
number_format forces the decimals on.

Beverleyh
09-03-2014, 05:23 AM
Or maybe str_replace();

Code:
<?php
$price = $ad['price'];
echo str_replace('.00', '', number_format($price, 2, '.', ','));
?>

qwikad.com
09-03-2014, 12:41 PM
I tried what you guys suggested but it didn't do the trick. I ended up going the long route:


<?php
$price = $ad['price'];
$price = number_format($price, 2, '.', ',');
$price = preg_replace('/\.00/', '', $price);
echo $price;
?>

I probably should change that preg_replace to str_replace eventually. Does the code above look silly to you?

Beverleyh
09-03-2014, 04:42 PM
Looks fine - very readable.

Yes, changing it to str_replace() will be slightly faster for a simple replacement - preg_replace() is more powerful and better suited to more complex replacements. A bit of speed test info is here: http://benchmarks.ro/2011/02/str_replace-vs-preg_replace/