0

I have following value which give wrong total.

let a = 86.2500;
let b = 32.3550;
alert(a+b);  //return 118.60499999999999  , expected 118.605
alert((a+b).toFixed(2))  //return 118.60   , expected 118.61

When I calculate above value with my calculator it give my expected result but javascript give me unexpected result. Why and what is solution to get expected result?

https://jsfiddle.net/vnu9fyb8/1/

Sadikhasan
  • 18,365
  • 21
  • 80
  • 122
  • @Sadikhasan This answer might help you https://stackoverflow.com/a/21323330/2943218 – Carsten Løvbo Andersen Nov 12 '19 at 12:40
  • https://jsfiddle.net/46jrd71t/ – Alive to die - Anant Nov 12 '19 at 12:40
  • @AnantSingh---AlivetoDie If you have calculator please calculate it what you get and let me know. Are you getting my expected result? If I am wrong then correct me to get my expected result. – Sadikhasan Nov 12 '19 at 12:42
  • 1
    See [Is floating point math broken](https://stackoverflow.com/questions/588004/is-floating-point-math-broken/588019#588019), which this duplicates. For exhaustive details see [What Every Computer Scientist Should Know About Floating Point Arithmetic](https://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html). – Dave Newton Nov 12 '19 at 12:53
  • 1
    One of the numbers cannot be represented precisely as binary value. You have the same issue in base 10 with `1/3`. – Felix Kling Nov 12 '19 at 12:54

2 Answers2

1

Try this to get the result:

let a = 86.2500;
let b = 32.3550;
alert((a+b).toFixed(3));
var digit = parseFloat((a+b).toFixed(3)).toFixed(2);
alert(digit);

I hope it will work for you.

ADDC
  • 103
  • 7
0

toFixed(2) cannot make it become 118.61 because of the full result is 118.60499999999999 so "6049" in front of 0 is number 4. 4 can't be floored up to be 5, but if in front of 0 is number 5 it sure will be floored up to 118.61.

So this can't become 118.61. You can refer to this link

rensothearin
  • 670
  • 1
  • 5
  • 24