Why was the difference in two rounded numbers not counting rounded values ​​in JavaScript?

I created a round function and it works fine with simple rounding.

If I round two numbers, A and B, and then add them, the result is perfect.

But if I "subtract" them, the result is strange. It is not rounded as it should.

I show you the following function:

function round(x, p) {
    return parseFloat(x.toFixed(p));
};

      

Strange result:

var a = 5.0007;
var b = 2.048
var result = round(5.0007, 3) - round(2.048, 2);

// expected result: 2.951
// obtained result: 2.9510000000000005

      

Here's a JSFiddle !

Can you help me understand why this subtraction is showing a strange result?

thank

+3


source to share





All Articles