- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Behavior of + operator in JavaScript to store large numbers?
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
Advertisements