Reputation: 14151
I have a variable that contains a price. It however takes the 0 from the price if it has cents. Such as $9.5 instead of $9.50. But if the price is $9.00 I want to display it as just $9.
Cents will not be displayed that often so that is why I want to keep the dollar amounts short but there will be the odd case that I will have cents but it just adds the zeros onto the dollars when there are no cents.
How would I cater for both scenarios in my code?
foreach($av as $day => $a){
if(isset($price[$ro['Room']['id']][$r['Rate']['id']][$day])){
$arr_total += $price[$ro['Room']['id']][$r['Rate']['id']][$day];
} else {
$errors[] = "No Set Price for $day";
}
Upvotes: 4
Views: 3633
Reputation: 48887
You can use:
number_format($price, !($price == (int)$price) * 2);
Examples:
$price = 9.01;
echo number_format($price, !($price == (int)$price) * 2);
// output: 9.01
$price = 9.00;
echo number_format($price, !($price == (int)$price) * 2);
// output: 9
Upvotes: 4
Reputation: 6431
There are a couple of core functions that may interest you
The first is money_format();
. This function is perfectly suited for your purposes, but it won't work on Windows systems. If you can guarantee your code won't ever be used on Windows, I would use this.
The second is number_format();
. Again, this function is well suited to your needs, but with the added advantage of being able to work on Windows. It doesn't, however, output formatted currency, but you can use it at least to get your decimal places.
Upvotes: 1
Reputation: 13461
pseudo-pseudo code:
if ($thePrice == intval($thePrice))
$thePrice = intval($thePrice);
else
$thePrice = money_format('%i', $thePrice);
See money_format()
Upvotes: 3
Reputation: 1064
When you get the value from the database it will probably be a string so you just have to convert it to a floting point number.
floatval($price)
Upvotes: 0
Reputation: 4530
Umm you simply try multiplying the number by 1. I THINK that might work, untested..
Upvotes: 0