Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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";
                            }
like image 521
Keith Power Avatar asked Feb 23 '23 22:02

Keith Power


1 Answers

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
like image 62
webbiedave Avatar answered Feb 27 '23 17:02

webbiedave