Reputation: 927
I have this code:
$string = '/([\d,]+)\.(\d+)(.*)$/';
$condition = preg_replace($string, '$2', $price);
if ($condition == 00) {
$show = preg_replace($string, '$1$3', $price);
} else {
$show = preg_replace($string, '$1.$2$3', $price);
}
So, if I have the price in this format: 100.00€ after the code is executed, the price is shown like this: 100€
But if I have the price in this format: $100.00 after the code is executed, the price is still shown like this: $100.00 i.e. the 00 is not trimmed (the second $show after the else statement is loaded).
The $price is generated with the currency symbol all together, so it's not just a pure number.
Any suggestions how can I make this happen, regardless the currency postion (left or right)?
Thanks.
P.S. It doesn't need to be this code, you can suggest another one, as long as it makes the 00 decimals to dissapear if equal to zero, regardles the position of the currecy symbol.
Upvotes: 1
Views: 1349
Reputation: 11971
<?php
$num = 126.54;
echo $num === round($num, 0) ? round($num, 0) : $num;
?>
That can be used to spit out your number. As far as currency position, you can set up a conditional for that depending on what the currency is.
FULL ANSWER: This handles all currency types and places them in their correct positions. Enjoy:
<?php
$symbols = array('€', '$');
$price = '$126.56';
foreach($symbols as $needle)
{
if($pos = strpos($price, $needle) && $pos !== false)
break;
}
$num = floatval(str_replace($symbols, '', $price));
$num = $num === round($num, 0) ? round($num, 0) : $num;
echo $pos ? $num.substr($price, -1) : substr($price, 0, 1).$num;
?>
KISS Method: Sometimes, we get so caught up in the complexities of answers, we lose sight of the simple ones. I know this is a little late, but it could potentially blow away a lot of unnecessary code. Use this ONLY if you are guaranteed to have two decimal places in your pricing:
<?php
$rounded = str_replace('.00', '', $price);
?>
What this will do is effectively eliminate any need to worry about Currency placement. But remember: This ONLY works for your case if you are guaranteed a pricing format of exactly two decimal places.
Upvotes: 3
Reputation:
This should help you:
UPDATE
Misread your original post and didn't realize you wanted to keep the currency symbol. This should do the trick nice and simple, and it doesn't matter what currency symbol it is, or where it is.
// Won't change this
$number = '$200.00';
echo preg_replace('/([.0-9]+)(€)/e','round(\'$1\',0)."$2"',$number);
// Will change this
$number = '200.00€';
echo preg_replace('/([.0-9]+)(€)/e','round(\'$1\',0)."$2"',$number);
Upvotes: 0