HighDots Forums  

Re: Math Problem

Javascript JavaScript language (comp.lang.javascript)


Discuss Re: Math Problem in the Javascript forum.



Reply
 
Thread Tools Display Modes
  #1  
Old   
Stephen Chalmers
 
Posts: n/a

Default Re: Math Problem - 10-05-2005 , 12:58 PM






McKirahan <News (AT) McKirahan (DOT) com> wrote

Quote:
How do I add floating point numbers accurately?

The following adds the 4 numbers
46.57, 45.00, 45.00, and 54.83 to give
191.39999999999998 instead of 191.40.
If you happen to be handling money, it's preferable to avoid floating point calculations by working in pennies, then
formatting the result.

var pennies=12305

var dollars=Math.floor( pennies / 100 ), cents = pennies % 100;

result = dollars + '.' + ((cents < 10) ? ('0' + cents) : cents);

--
S.C.






Reply With Quote
Reply




Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off



Powered by vBulletin Version 3.5.4
Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.