Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 852
zerkms Avatar asked Apr 22 '21 23:04

zerkms


People also ask

How to remove a number from integer in JavaScript?

The Math. trunc() is the most popular method to remove the decimal part of JavaScript. It takes positive, negative, or float numbers as an input and returns the integer part after removing the decimal part. For example, when we give an input of 5.45, it returns 5 only, and for the input of -5.45, it returns -5 only.

How do you cut a number in JavaScript?

In JavaScript, trunc() is a function that is used to return the integer portion of a number. It truncates the number and removes all fractional digits. Because the trunc() function is a static function of the Math object, it must be invoked through the placeholder object called Math.


Video Answer


1 Answers

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).

like image 195
Eric Postpischil Avatar answered Oct 23 '22 00:10

Eric Postpischil