Skip to content
Advertisement

Why is 5726718050568503296 truncated in JS

As per the standard ES implements numbers as IEEE754 doubles.

And per https://www.binaryconvert.com/result_double.html?decimal=053055050054055049056048053048053054056053048051050057054 and other programming languages https://play.golang.org/p/5QyT7iPHNim it looks like the 5726718050568503296 value can be represented exactly without losing precision.

Why it loses 3 significant digits in JS (reproduced in latest stable google chrome and firefox)

This question was triggered initially from the replicate javascript unsafe numbers in golang

The value is definitely representible in double IEEE754, see how naked bits are converted to a float64 in Go: https://play.golang.org/p/zMspidoIh2w

Advertisement

Answer

The default rule for JavaScript when converting a Number value to a decimal numeral is to use just enough digits to distinguish the Number value. Specifically, this arises from step 5 in clause 7.1.12.1 of the ECMAScript 2017 Language Specification, per the linked answer. (It is 6.1.6.1.20 in the 2020 version.)

So while 5,726,718,050,568,503,296 is representable, printing it yields “5726718050568503000” because that suffices to distinguish it from the neighboring representable values, 5,726,718,050,568,502,272 and 5,726,718,050,568,504,320.

You can request more precision in the conversion to string with .toPrecision, as in x.toPrecision(21).

Advertisement