PHP format price in variable
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";
}
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
pseudo-pseudo code:
if ($thePrice == intval($thePrice))
$thePrice = intval($thePrice);
else
$thePrice = money_format('%i', $thePrice);
See money_format()
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.
Umm you simply try multiplying the number by 1. I THINK that might work, untested..
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)
精彩评论