Home > Mobile >  I hava a very simple question about Math.round() in javascript
I hava a very simple question about Math.round() in javascript

Time:12-29

code:

let result;

result = 2.4999999999999998;
console.log(Math.round(result));

result = 2.4999999999999997;
console.log(Math.round(result));

The rounding point isn't 5 ? (Although I know that numbers in JavaScript always occupy 64 bits of memory. Numbers up to 15 integer digits and 17 decimal digits can be defined and displayed in JavaScript.) why the result in console is:

result in console

I expected the both are: 3

CodePudding user response:

Your input values have more digits of precision than JS floats can hold, so the last digit is being rounded to the nearest binary value. This causes the first one to be read as 2.5, and Math.round() rounds this to 3.

You can see this by printing the values of result before rounding.

let result;

result = 2.4999999999999998;
console.log(result, Math.round(result));

result = 2.4999999999999997;
console.log(result, Math.round(result));

CodePudding user response:

That extra 1 at the end of 2.4999999999999998 results in it being too close to 2.5 for JavaScript to recognize a difference.

const withEight = 2.4999999999999998;
console.log(2.4999999999999998 === 2.5)

So Math.round(2.4999999999999998) is the same as Math.round(2.5).

And, as the specification requires that, when a number is rounded that is exactly between two integers, the higher integer is preferred.

  1. Return the integral Number closest to n, preferring the Number closer to ∞ in the case of a tie.

So 3 is the result.

  • Related