Search code examples
javascriptsubtraction

JavaScript arithmetic subtraction giving extra unwanted decimal digits


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?


Solution

  • You can use .toFixed:

    var a = 8.4286;
    var b = 2;
    let sub = a-b;
    sub = sub.toFixed(4);
    console.log(sub);