Welcome to WebmasterWorld Guest from 54.161.228.30

Forum Moderators: coopster & jatar k

Message Too Old, No Replies

What to do when 28.55 + 0 = 29?

involuntary rounding

   
12:19 am on Aug 7, 2010 (gmt 0)

10+ Year Member



I can not figure this out. I've searched for rounding issues. I'm experimenting with an E-Bay search API. The API returns a value of 28.55 for the price and 0 for the shipping. I simply want to add these two variables together, and when I do, it rounds them to whole numbers (29).

I've tried adding $total = ($price + .0001) + ($shipping + .0001); and it does the same thing. I've used ROUND, I've used SPRINTF. Nothing works. When I print_r the returned API array, the correct values are there right in front of me. What in the heck is going on here?
12:55 am on Aug 7, 2010 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Hi.

It sounds to me like one of two things is happening:

a. It could be that your variables are being eveluated as integers [php.net] instead of floating point numbers [php.net].

Try type casting the variables, something like this:

$total = (float) $price + (float) $shipping;


It seems like this should not be the problem though, because adding a float number to your variables (as you show above) should have triggered PHP's automatic type conversion [php.net].

b. It could also be that something in your script is formatting or otherwise interfering with the returned value for output. I don't think we can say if this is the case without more code...

-- b
4:03 am on Aug 7, 2010 (gmt 0)

10+ Year Member



The (float) worked! Weird. Just when I think I'm finally getting a grip on PHP, I get thrown a curve like this. Thanks for your help bedlam.
6:44 pm on Aug 7, 2010 (gmt 0)

WebmasterWorld Senior Member rocknbil is a WebmasterWorld Top Contributor of All Time 10+ Year Member



Float can do some weird things due to floating point precision which is device dependent, it kicks me all the time in Javascript. For future reference,

$total = sprintf("%.2f",intval(($price*100)+($shipping*100))/100);

sprintf **is** a string operator, and this seems kinda complex, but it's reliable in about any language. :-)