In this article, we will show you the difference between BigInt and BigInt number data types in JavaScript. And also when to use the BigInt data type
You cannot store 100.20 in a BigInt, because it is an integer and not decimal.
//bigInt
var BigNum1=100n; //ok
var BigNum2=100.20n; /error
//number
var Num1=100; //ok
var Num2=100.20; /ok
bigInt is stored as arbitrary-precision integers and the number as double-precision 64-bit number.
The number can handle numbers up to 9007199254740991 ( Number.MAX_SAFE_INTEGER). It is a limitation imposed due to the double precision 64 bit number
The BigInt can handle numbers larger than that. BigInt is limited by the available memory of the host system.
Since they are integers, they do not suffer from Floating-point precision problems. Hence operations involving them are more precise.
bigint can not be mixed with operations where numbers are involved as shown below. The JavaScript will throw Cannot mix BigInt and other types, use explicit conversions error.
let numVar=100;
let bigVar= 100n;
console.log(numVar+bigVar);
*** Error *****
Cannot mix BigInt and other types, use explicit conversions
We cannot use a BigInt value with methods in the built-in Math object as it only supports number types.
You can convert bigInt to a number using the Number function. But if the bigInt number is larger than Number.MAX_SAFE_INTEGER then you will loose precision
let numVar=100;
let bigVar= 100n;
console.log(numVar+ Number(bigVar)); //200
Convert the number to bigInt, but if the number is a decimal number, then you will loose the precision again as bigInt is integer and not decimal.
Comparing a bigInt with a number works correctly.
console.log(1n < 2) //true
console.log(2n > 1) //true
console.log(2n > 2) //false
console.log(2n >= 2) //true
Comparing a bigInt with a number works correctly.BigInt is loosely equal to number, But if you use strict equality checker (===) then they are not equal as they differ in their data type
let numVar=100;
let bigVar= 100n;
console.log(numVar==bigVar) //true
console.log(numVar===bigVar) //false
The arithmetic operations involving BigInt are slower compared to the Floating Point arithmetic of a primitive number.
The floating-point arithmetic is implemented in hardware, Hence it is faster. The Arbitrary-precision arithmetic is entirely implemented in software hence slower.
Always use numbers unless you need to support numbers larger than Number.MAX_SAFE_INTEGER.
Read More