如何避免在JavaScript中使用科学计数法表示大量数字?

当数字变大时,JavaScript会将 转换为 。如何防止这种情况发生?

回答:

有Number.toFixed,但如果数字>=1e21且最大精度为20,它将使用科学计数法。除此之外,您可以自己滚动,但会很混乱。

function toFixed(x) {

if (Math.abs(x) < 1.0) {

var e = parseInt(x.toString().split('e-')[1]);

if (e) {

x *= Math.pow(10,e-1);

x = '0.' + (new Array(e)).join('0') + x.toString().substring(2);

}

} else {

var e = parseInt(x.toString().split('+')[1]);

if (e > 20) {

e -= 20;

x /= Math.pow(10,e);

x += (new Array(e+1)).join('0');

}

}

return x;

}

上面使用便宜的’n’-简单字符串重复((newArray(n+1)).join(str))。您可以定义String.prototype.repeat使用俄罗斯农民乘法,而改为使用它。

此答案应仅适用于以下问题:显示大量而不使用科学计数法。除此之外,您应该使用BigInt库,例如BigNumber,Leemon’s

BigInt或BigInteger。展望未来,新的本地BigInt(注:不是Leemon’s)应该可用;Chromium和基于它的浏览器([Chrome,新的Edge[v79+],Brave)和Firefox均受支持;Safari的支持正在进行中。

这是使用BigInt的方法: BigInt(n).toString()

例:

const n = 13523563246234613317632;

console.log("toFixed (wrong): " + n.toFixed());

console.log("BigInt (right): " + BigInt(n).toString());

,作为JavaScript数字(不是BigInt)输出的任何大于15-16位(特别是大于Number.MAX_SAFE_INTEGER +

1[9,007,199,254,740,992])的整数都应四舍五入,因为JavaScript的数字类型(IEEE-754双精度)浮点数)不能精确地保存该点以外的所有整数。由于Number.MAX_SAFE_INTEGER

+

1它以2的倍数工作,因此它不再容纳奇数(并且类似地,它以18,014,398,509,481,984开始以4的倍数工作,然后是8,然后是16,…)。

因此,如果您可以依靠BigInt支持,则将您的数字作为字符串输出,然后传递给该BigInt函数:

const n = BigInt("YourNumberHere");

例:

const n1 = BigInt(18014398509481985); // WRONG, will round to 18014398509481984

// before `BigInt` sees it

console.log(n1.toString() + " <== WRONG");

const n2 = BigInt("18014398509481985"); // RIGHT, BigInt handles it

console.log(n2.toString() + " <== Right");

以上是 如何避免在JavaScript中使用科学计数法表示大量数字? 的全部内容, 来源链接: utcz.com/qa/435926.html

回到顶部