Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations TouchToneTommy on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

0.1 + 0.2 = 0.300000000004 (?!?)

Status
Not open for further replies.

DaZZleD

Programmer
Oct 21, 2003
886
US
anyone ever tried:

Code:
x = parseFloat(0.1) + parseFloat(0.2);
document.Write(x);

it will return 0.30000000000004

this is strange... anyone got an explanation?
 

>> anyone got an explanation?

Yes. Computers don't work in floating point - they can only work in binary, so to do any FP calculations requires them to emulate FP routines.

This conversion process will invariably cause rounding errors at some stage, which is what you are seeing.

Incidentally, you do not need to use parseFloat in the example you gave, as the two values are FP numbers, not strings, so that will save you a few CPU cycles ;o)

Hope this helps,
Dan
 
I did that just to simplyfy the example. actually, the two values are taken from textboxes and therefore are strings.

thanks for the answer anyway!
 
DaZZleD,

I don't know if you are just thinking out loud or if you were looking for a way to round that number off, but a quick-trick would be:

Code:
x = parseFloat(0.1) + parseFloat(0.2);
x = x * 10;
x = Math.round(x);
x = x/10;

//or, in one step:
x = Math.round((parseFloat(0.1) + parseFloat(0.2))*10)/10

--Dave
 
I was just looking for an explanation to this strange result. :D
 
I'll go back to sitting on my hands then. :)

--Dave
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top