104

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
2
  • I am not saying this will help with this question. But I always like to point out this article in times like this Commented Sep 20, 2012 at 10:50
  • 1
    While 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. Commented Sep 4, 2015 at 17:33

2 Answers 2

193

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
Sign up to request clarification or add additional context in comments.

4 Comments

Simply use parseFloat((2.3 + 2.4).toFixed(10)) Here is the explanation
Pay attention that toFixed(fractionDigits) returns a string
this is not a real solutions whereas my numbers are different 1+1.2+1.25+4.5=???
@Monzur—you can do toFixed on the result: Number((1+1.2+1.25+4.5).toFixed(10)) will return a number. If you need more than 10 decimal places you might need to use BigInt instead.
14
(parseFloat('2.3') + parseFloat('2.4')).toFixed(1);

its going to give you solution i suppose

answered Sep 20, 2012 at 10:58

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.