Search code examples
phpebay-api

PHP; sum of returned numbers from eBay API is invalid


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.