homepage Welcome to WebmasterWorld Guest from
register, free tools, login, search, pro membership, help, library, announcements, recent posts, open posts,
Become a Pro Member
Home / Forums Index / Code, Content, and Presentation / PHP Server Side Scripting
Forum Library, Charter, Moderators: coopster & jatar k

PHP Server Side Scripting Forum

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

 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?



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


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)

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)

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. :-)

Global Options:
 top home search open messages active posts  

Home / Forums Index / Code, Content, and Presentation / PHP Server Side Scripting
rss feed

All trademarks and copyrights held by respective owners. Member comments are owned by the poster.
Home ¦ Free Tools ¦ Terms of Service ¦ Privacy Policy ¦ Report Problem ¦ About ¦ Library ¦ Newsletter
WebmasterWorld is a Developer Shed Community owned by Jim Boykin.
© Webmaster World 1996-2014 all rights reserved