Question

I need to refresh the cart page and show a custom block in case my Grand Totals is Negative.

$grandTotal = Mage::helper('checkout/cart')->getQuote()->getGrandTotal();

This prints -$2,269.50, but when I use the below condition, it just don't work.

If ($grandTotal < 0 ){
//do something
}else{
//do something else
}

How can I check if number is less than 0 i.e. negative

Thanks

Was it helpful?

Solution

Your problem is that getGrandTotal is returning a string rather then a number. Trying to see if a string is lower then 0 isn't going to work.

You can filter the string and remove anything which isn't a number using

filter_var($grandTotal, FILTER_SANITIZE_NUMBER_INT);

Which in your case would return -226950 which you can then check if it's lower then 0, if you need to do further checks you'll need to handle the way it removes the separator between the pounds and pence.

if(filter_var($price,FILTER_SANITIZE_NUMBER_INT) < 0) {
    // Do something
} else {
    // Do something else
}

OTHER TIPS

If you want the exact amount as well, you can use

$currency_sign = "$";
$actual_amount = str_replace($currency_sign,'',$grandTotal); // $grandTotal is -$2,269.50
if($actual_amount < 0) { //$actual_amount will have the value as -2,269.50
    // Do something
} else {
    // Do something else
}

all you need is to use the correct currency sign. You can get the current currency sign by the following code:

Mage::app()->getLocale()->currency(Mage::app()->getStore()->getCurrentCurrencyCode())->getSymbol();

i suggest that instead of use

$grandTotal = Mage::helper('checkout/cart')->getQuote()->getGrandTotal();

please use

$quote = Mage::helper('checkout/cart')->getQuote();
$quoteData= $quote->getData();
$grandTotal=$quoteData['grand_total'];

it give proper integer/float value.

Licensed under: CC-BY-SA with attribution
Not affiliated with magento.stackexchange
scroll top