JavaScript 中 + 運算子用於儲存大數字的行為?


要儲存 JavaScript 中的大數字,請使用 BigInt() 而不是 + 運算子。如果您將使用 + 運算子,則預計精度將會降低。

假設以下是我們的大數字,我們使用 BigInt() 儲存這個數字 -

console.log("Loss of precision with + operator..")

示例

以下是程式碼 -

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

更新於: 2020 年 10 月 3 日

2K+ 瀏覽量

啟動您的職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.