98

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...)

Community
  • 1
  • 1
davioooh
  • 23,742
  • 39
  • 159
  • 250
  • I am not saying this will help with this question. But I always like to point out [this article](http://www.codeproject.com/Articles/182416/A-Collection-of-JavaScript-Gotchas) in times like this – musefan Sep 20 '12 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. – Malavos Sep 04 '15 at 17:33

2 Answers2

187

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));​
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • 11
    Simply use `parseFloat((2.3 + 2.4).toFixed(10))` [Here](https://stackoverflow.com/a/51723472/4344976) is the explanation – Muhammad Musavi Aug 07 '18 at 09:36
  • 5
    Pay attention that `toFixed(fractionDigits)` returns a string – Artem Fedotov Sep 05 '20 at 09:21
  • this is not a real solutions whereas my numbers are different 1+1.2+1.25+4.5=??? – Monzur Sep 11 '21 at 11:04
  • @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*](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) instead. – RobG Dec 28 '21 at 23:16
13
(parseFloat('2.3') + parseFloat('2.4')).toFixed(1);

its going to give you solution i suppose