JavaScript 中 + 运算符存储大数的行为?
javascriptweb developmentfront end technologyobject oriented programming更新于 2026/1/2 8:12:17
要在 JavaScript 中存储大数,请使用 BigInt() 而不是 + 运算符。如果您使用 + 运算符,则会出现精度损失。
假设以下是我们的大型数字,我们使用 BigInt() 存储 −
console.log("使用 + 运算符会损失精度。")
示例
以下是代码 −
var stringValue1="100";
console.log("The integer value=");
console.log(+stringValue1);
var stringValue2="2312123211345545367";
console.log("Loss of precision with + operator..")
console.log(+stringValue2);
const storeLongInteger=BigInt("2312123211345545367");
console.log("No loss of precision with BigInt()");
console.log(storeLongInteger);
要运行上述程序,您需要使用以下命令 −
node fileName.js.
这里我的文件名是 demo212.js。
输出
控制台上的输出如下 −
PS C:\Users\Amit\JavaScript-code> node demo213.js The integer value= 100 Loss of precision with + operator.. 2312123211345545000 No loss of precision with BigInt() 2312123211345545367n
相关文章
有用资源
javascript 参考教程 - 该教程包含有关 javascript 的更多信息:https://www.cainiaomax.com/javascript/

