[英]toString() returns different value than expected (however toFixed returns the right one). Why?
为什么 toString() 返回的值与预期不同? 我希望 toString 结果与 toFixed 结果相同。
const a = 2929539092180640938;
console.log(a.toString());
// prints '2929539092180641000'
console.log(a.toFixed());
// prints '2929539092180640938'
由于这个“特性”,像这样简单而正确的行给出了完全不可预测的结果const b = `Value ${a}`;
这些都不能准确地打印数字,因为 2929539092180640938 高于Number.MAX_SAFE_INTEGER
,即9007199254740991
。
调用.toFixed
会给你 2929539092180640768。
调用.toString
会给你 2929539092180641000。
.toFixed
的结果有时可能与.toString
不同(并且更准确) ,因为:
toFixed 的 output 对于某些值可能比 toString 更精确,因为 toString 只打印足够的有效数字来区分数字和相邻的 Number 值。 例如,
(1000000000000000128).toString() returns "1000000000000000100",
尽管
(1000000000000000128).toFixed(0) returns "1000000000000000128".
a
中的数字大于Number.MAX_SAFE_INTEGER
(2^53-1),所以这么大数字的字符串转换可能会有精度损失。
如果您使用BigInt
, toString() 将按预期工作:
const b = BigInt('2929539092180640938');
console.log(b.toString()); //2929539092180640938
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.