Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Javascript

พฤติกรรมของตัวดำเนินการ + ใน 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