为什么在JS中将5726718050568503296截断 [英] Why is 5726718050568503296 truncated in JS
问题描述
根据标准 ES将数字实现为IEEE754加倍.
As per the standard ES implements numbers as IEEE754 doubles.
并且根据 https://www.binaryconvert.com/result_double.html?decimal=053055050054055049056048053048053054056053048051050057054 和其他编程语言 https://play.golang.org/p/5QyT7iPHNim看起来 5726718050568503296
值可以精确地表示而不会损失精度.
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.
为什么它在JS中丢失3个有效数字(最新稳定的Google chrome和firefox中转载了此内容)
Why it loses 3 significant digits in JS (reproduced in latest stable google chrome and firefox)
此问题最初是从在golang中复制javascript不安全数字触发的
该值绝对可以在双IEEE754中表示,请参阅如何在Go中将裸比特转换为float64: https://play.golang.org/p/zMspidoIh2w
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
推荐答案
转换 Number <时JavaScript的默认规则/code>值转换为十进制数字是使用足够的数字来区分
Number
值.具体来说,这是根据链接的答案来自ECMAScript 2017语言规范第7.1.12.1节中的第5步产生的.(2020年版本为6.1.6.1.20.)
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.)
因此,虽然可以表示5,726,718,050,568,503,296,但打印时会产生"5726718050568503000",因为足以将其与相邻的可表示值(5,726,718,050,568,502,272和5,726,718,050,568,504,320)区分开来.
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.
与 x.toPrecision(21)
中一样,您可以请求使用 .toPrecision
转换为字符串时更精确.
You can request more precision in the conversion to string with .toPrecision
, as in x.toPrecision(21)
.
这篇关于为什么在JS中将5726718050568503296截断的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!