PHP; sum of returned numbers from eBay API is invalid
Question
I seem to be having an issue with PHP rounding (sort of) numbers by default, I am calling the eBay API and getting back the price of an item and the postage. I need to add these two numbers before entering them into my database, the issue seems to be when I add the two numbers up they come back with a strange value:
shipping = 5.95
item price = 18.55
If I add the two up I get a result of 23
.
$ship = $item->shippingInfo->shippingServiceCost;
$price = $item->sellingStatus->currentPrice;
$sell = ($ship + $price);
Do I need to tell php the returned value is a number?
Solution
Make sure both of your values are actually integers or floats, instead of strings. Summing strings to eachother could result in strange behavior.
Try this:
$ship = (float) $item->shippingInfo->shippingServiceCost;
$price = (float) $item->sellingStatus->currentPrice;
$sell = ($ship + $price);
Now $sell should consist of a float. You can use (float)
to cast the variable to a floating variable.
OTHER TIPS
Take a look at typecasting in general, as is quite important in a variety of scenarios for you as a PHP developer.
The problem is not the $ship is a string with 5.95
.. that would be properly converted to float but I think it is .. 5,95
and that would be converted to 5
<?php
$ship = "5,95";
$price = "18,55";
$sell = ($ship + $price);
echo "$sell = ($ship + $price)";
?>
output:
23 = (5,95 + 18,55)
convert:
<?php
$ship = (float) "5,95";
$price = (float) "18,55";
$sell = ($ship + $price);
echo "$sell = ($ship + $price)";
?>
output:
23 = (5 + 18)
Use:
$ship = str_replace(',','.',$ship);
$price = str_replace(',','.',$price);
And it should work!