问题
The code below is in PHP and returns prices from a XML response file.
$price = $result->Items->Item->OfferSummary->LowestNewPrice->FormattedPrice; //lowest new price
$listPrice = $result->Items->Item->Offers->Offer->OfferListing->Price->FormattedPrice; //list price
If I echo $price or $listPrice it works
I wish to get the difference between the two prices but I am getting NULL if I do
$savings = $listPrice - $price; or $savings = ($listPrice - $price);
Any assistance is welcome
回答1:
You're most likely trying to subtract a string from a string. You need to convert the values to a numeric type. If you're working with prices, you'll probably want floating point numbers:
$price = floatval($result->Items->Item->OfferSummary->LowestNewPrice->FormattedPrice); //lowest new price
$listPrice = floatval($result->Items->Item->Offers->Offer->OfferListing->Price->FormattedPrice); //list price
$savings = $listPrice - $price;
回答2:
I assume $price and $listprice are numbers (integers or doubles), so it is possible they appear to be numbers when echoing them alone, but they could be strings with whitespace that is preventing them from being parsed. Try using trim() to remove whitespace (eg, $price = trim($price)).
回答3:
While they may appear to be numbers, it may be worth it to cast them to floats, just to make sure.
$savings = floatval($listPrice) - floatval($price);
来源:https://stackoverflow.com/questions/16001102/basic-mathematics-in-php-simplexml