Behavior of + operator in JavaScript to store large numbers?

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

To store large numbers in JavaScript, use BigInt() rather than + operator. If you will use the + operator, then expect loss of precision.

Let’s say the following is our large number and we are storing using BigInt() −

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

Example

Following is the code −

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);

To run the above program, you need to use the following command −

node fileName.js.

Here, my file name is demo212.js.

Output

The output is as follows on console −

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
raja
Updated on 03-Oct-2020 12:38:27

Advertisements