homepage Welcome to WebmasterWorld Guest from 23.20.63.27
register, free tools, login, search, pro membership, help, library, announcements, recent posts, open posts,
Become a Pro Member

Visit PubCon.com
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
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. :-)

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