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
javascript rounding subtraction addition


source to share


No one has answered this question yet

See similar questions:

2745
Is floating point math broken?

or similar:

7287
What does "use strict" do in JavaScript, and what are the reasons for it?
3953
What value of "href" should be used for JavaScript references, "#" or "javascript: void (0)"?
3915
Why does Google add while (1); into your JSON responses?
2701
How do I get the values ​​of a query string in JavaScript?
2303
Checking decimal numbers in JavaScript - IsNumeric ()
2284
How can I combine properties of two JavaScript objects dynamically?
2256
Set default parameter value for JavaScript function
1949
How does JavaScript.prototype work?
1597
Generating a random number between two numbers in JavaScript
1192
How to round a number to n decimal places in Java



All Articles
Loading...
X
Show
Funny
Dev
Pics