1
var a = 8.4286;
var b = 2;
console.log(a-b)

Actual Output: 6.428599999999999

Expected Output: 6.4286

What is the reason behind this and how to get around it?

1 Answers1

1

You can use .toFixed:

var a = 8.4286;
var b = 2;
let sub = a-b;
sub = sub.toFixed(4);
console.log(sub);
Majed Badawi
  • 27,616
  • 4
  • 25
  • 48
  • The same question is already asked and answered here: https://stackoverflow.com/questions/588004/is-floating-point-math-broken as `parseFloat((a - b).toFixed(4));` where 4 is the number of decimal digits wanted. – Raj Rajeshwar Singh Rathore Aug 06 '20 at 12:41