| What to do when 28.55 + 0 = 29? involuntary rounding |
salewit

msg:4183395 | 12:19 am on Aug 7, 2010 (gmt 0) | 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?
|
bedlam

msg:4183410 | 12:55 am on Aug 7, 2010 (gmt 0) | 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
|
salewit

msg:4183468 | 4:03 am on Aug 7, 2010 (gmt 0) | 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.
|
rocknbil

msg:4183673 | 6:44 pm on Aug 7, 2010 (gmt 0) | 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. :-)
|
|
|