Float sum with javascript

JavascriptMathFloating Point

Javascript Problem Overview


> Possible Duplicate:
> Is JavaScript's Math broken?

I'm calculating the sum of several float values using javascript and... I've noticed a strange thing never seen before. Executing this code:

parseFloat('2.3') + parseFloat('2.4')

I obtain 4.699999999999999

So... what sould I do to obtain a correct value? (supposed that this is incorrect...)

Javascript Solutions


Solution 1 - Javascript

Once you read what What Every Computer Scientist Should Know About Floating-Point Arithmetic you could use the .toFixed() function:

var result = parseFloat('2.3') + parseFloat('2.4');
alert(result.toFixed(2));​

Solution 2 - Javascript

(parseFloat('2.3') + parseFloat('2.4')).toFixed(1);

its going to give you solution i suppose

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiondaviooohView Question on Stackoverflow
Solution 1 - JavascriptDarin DimitrovView Answer on Stackoverflow
Solution 2 - JavascriptGyan Chandra SrivastavaView Answer on Stackoverflow