0

I have an application which read API return string from a website and compare it to a value to see if it is greater or equal to particular float, the API return two float String which is "2366.5876" and "4067.4076" which when we add up equal to 6433.9952

But what I tried on Javascript provide different result:

cumulative = 0;
cumulative += parseFloat("2366.5876")
cumulative += parseFloat("4067.4076")
//here it return 6433.995199999999 instead of 6433.9952 . Why??

which when I compare to 6433.9952 , produce false which is not intended

cumulative >= 6433.9952 //False ???

Can I know how can I solve this??

dramasea
  • 3,370
  • 16
  • 49
  • 77
  • `parseFloat` is fine. It's the addition of floats that produces a different number. – VLAZ Dec 03 '20 at 18:13
  • @VLAZ Do you know why it perform so? Any way that we could get the correct value? – dramasea Dec 03 '20 at 18:15
  • There is a linked dupe. Here are more resources: https://0.30000000000000004.com/ | [What Every Computer Scientist Should Know About Floating-Point Arithmetic](https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html) | [What Every Programmer Should Know About Floating-Point Arithmetic](https://floating-point-gui.de/) | [How to deal with floating point number precision in JavaScript?](https://stackoverflow.com/q/1458633) – VLAZ Dec 03 '20 at 18:19
  • Consider that between 6433.9951 and 6433.9952 are infinite real numbers, and yet your computer has finite memory. You're going to have to approximate at some point. – James Dec 03 '20 at 18:34
  • @James that's misleading as these two numbers *aren't* infinite. Not when in decimal. The problem is that the binary representation of them is imprecise and performing mathematical operations with imprecise numbers leads to a cumulative error. – VLAZ Dec 03 '20 at 18:50
  • @VLAZ The numbers are indeed finite but there is an infinity of other finite numbers between them. It would be impossible for a computer to assign a different representation to each of them. – James Dec 03 '20 at 19:01

0 Answers0