mk_89
mk_89

Reputation: 2742

Always getting wrong value when adding two up numbers

This is one of the most bizarre problems I've run into so far, I have two numbers which I am trying to add up in php but for some reason php does not give me the correct result.

I am trying to add the $itemPrice with the $shipPrice which is 3.50 + 2.80 that should give me 6.30 but instead I get 5.

I have tried using the floatVal() function but that makes no difference, does anyone have any ideas?

below is a sample of the code

php code

foreach($resp->ListOrderItemsResult->OrderItems->OrderItem as $order){
   $itemPrice =  $order->ItemPrice->Amount;
   $shipPrice = $order->ShippingPrice->Amount;
   $total = $itemPrice + $shipPrice;

   $arr[] = array(
      'sku' => $order->SellerSKU,
      'isbn' => $order->ASIN,
      'title' => $order->Title,
      'item_price' => $itemPrice,
      'ship_price' => $shipPrice,
      'total' => $total,
      'quantity_shipped' => $order->QuantityShipped,
   );
}

output

sku             isbn         title  item_price  ship_price  total   quantity_shipped
VM-F5TU-BN0K    1844831531   xxxxx  3.50        2.80            5   1

Upvotes: 0

Views: 150

Answers (4)

Travis Pessetto
Travis Pessetto

Reputation: 3298

I know quite a few programmer that instead of dealing with decimals will put the price in cents then convert the cents into a dollar amount. You may be able to find more information on this by goggling "PHP virtual attributes."

This prevents rounding errors and the like. Plus integers are handled better by computers.

Upvotes: 1

Tony M
Tony M

Reputation: 8302

$total = (float) $itemPrice + (float) $shipPrice;

Upvotes: 1

user1350140
user1350140

Reputation:

Check the amount datatype output and the datatype of price fields in your database.

Upvotes: 2

Mike Brant
Mike Brant

Reputation: 71384

My guess is that $itemPrice and $shipPrice are strings and when you try to add them together you are getting a value of 5. Make sure you are specifically casting the $itemPrice and $shipPrice as floats if there are stored in your object as strings.

Upvotes: 5

Related Questions