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...)
asked Sep 20, 2012 at 10:47
davioooh
24.8k47 gold badges172 silver badges262 bronze badges
-
I am not saying this will help with this question. But I always like to point out this article in times like thismusefan– musefan2012年09月20日 10:50:27 +00:00Commented Sep 20, 2012 at 10:50
-
1While searching for this, I do not see how this question is duplicate - the problem is not solved on the question marked as duplicate, and still, in the whole SO, I have not found a proper solution for the same problem.Malavos– Malavos2015年09月04日 17:33:08 +00:00Commented Sep 4, 2015 at 17:33
2 Answers 2
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));
answered Sep 20, 2012 at 10:50
Darin Dimitrov
1.0m276 gold badges3.3k silver badges3k bronze badges
Sign up to request clarification or add additional context in comments.
4 Comments
Muhammad Musavi
Simply use
parseFloat((2.3 + 2.4).toFixed(10)) Here is the explanationArtem Fedotov
Pay attention that
toFixed(fractionDigits) returns a stringMonzur
this is not a real solutions whereas my numbers are different 1+1.2+1.25+4.5=???
(parseFloat('2.3') + parseFloat('2.4')).toFixed(1);
its going to give you solution i suppose
answered Sep 20, 2012 at 10:58
Gyan Chandra Srivastava
1,38010 silver badges29 bronze badges
Comments
lang-js