เพื่อเก็บตัวเลขขนาดใหญ่ใน JavaScript ให้ใช้ BigInt() แทนตัวดำเนินการ + หากคุณใช้ + operator คาดหวังความสูญเสียของความแม่นยำ
สมมติว่าต่อไปนี้คือตัวเลขขนาดใหญ่ของเรา และเราเก็บด้วย 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