Shumii
Shumii

Reputation: 4581

I cannot understand the results of these simple additions in Javascript. Is there something like rounding affecting?

In Javascript when I do the following additions:

console.log(42.458333333333336+21)
console.log(42.458333333333336+22)

I expected this to output:

63.458333333333336
64.458333333333336

But it does not, it outputs:

63.458333333333336
64.45833333333334

What's going on with that then?

Upvotes: 1

Views: 39

Answers (1)

Eric Postpischil
Eric Postpischil

Reputation: 222938

The difference in display is caused by JavaScript’s default formatting of floating-point numbers. JavaScript uses just enough digits to uniquely distinguish the number from adjacent representable values.

When 42.458333333333336 appears in source code, it is converted to the nearest value representable in the Number format, which is 42.45833333333333570180911920033395290374755859375.

Adding 21 to this produces 63.45833333333333570180911920033395290374755859375. The next higher Number is 63.458333333333342807236476801335811614990234375. If these were rounded to 16 significant decimal digits, they would have the same result, 63.4583333333333. So JavaScript rounds your result to 17 digits to distinguish it, producing “63.458333333333336”.

When 22 is added to 42.45833333333333570180911920033395290374755859375, the result is 64.458333333333342807236476801335811614990234375. Note that this went past 64, so the exponent used to represent it in base-two floating-point has increased. That means it loses some absolute precision. The result was rounded to fit in the floating-point format, so the fraction portion changed. The next lower Number is 64.4583333333333285963817615993320941925048828125. For these two numbers, only 16 significant digits are needed to distinguish them, because they round to 64.45833333333334 and 64.45833333333333. So JavaScript produces “64.45833333333334”.

Upvotes: 1

Related Questions