JavaScript BigInt


JavaScript Integer Accuracy

JavaScript integers are only accurate up to 15 digits:

In JavaScript, all numbers are kept in a particular way called '64-bit floating-point format' based on the IEEE 754 standard.

This rule means that really big numbers can't be shown exactly and will be approximated.

Because of this, JavaScript can only safely represent integers:

Maximum: 9,007,199,254,740,991 + (9,007,199,254,740,991 - 1)

and

Decreasing to a very large negative number, which is equivalent to -9007199254740991, and it is specifically one less than two to the power of 53.

Integer values outside this range lose precision.


How to Create a BigInt

To make a **BigInt**, add 'n' at the end of a whole number, or use the function **BigInt()**.


BigInt: A new JavaScript Datatype

In JavaScript, when you use the typeof operator on a variable that contains a BigInt, it will return "bigint".

In JavaScript, we have another numeric data type called BigInt. It comes right after the "Number" data type.

JavaScript can handle 8 different data types, including BigInt.

1. String
2. Number
3. Bigint
4. Boolean
5. Undefined
6. Null
7. Symbol
8. Object


BigInt Operators

You can use the same operations on a JavaScript Number as you can on a BigInt.

Notes : You can't perform arithmetic directly between a BigInt and a Number because it may lead to loss of information due to type conversion.

Unsigned right shift (>>>) can not be done on a BigInt (it does not have a fixed width).


BigInt Decimals

A BigInt doesn't support decimal numbers.


BigInt Hex, Octal and Binary

BigInt can also be written in hexadecimal, octal, or binary notation:


Precision Curiosity

Rounding can make a program less secure.


Minimum and Maximum Safe Integers

ES6 added max and min properties to the Number object:

  • MAX_SAFE_INTEGER
  • MIN_SAFE_INTEGER

New Number Methods

ES6 also added 2 new methods to the Number object:

  • Number.isInteger()
  • Number.isSafeInteger()

The Number.isInteger() Method

The Number.isInteger() function checks if the given value is a whole number and returns true if it is.


The Number.isSafeInteger() Method

A safe integer is a whole number that can be precisely expressed as a double precision number.

The Number.isSafeInteger() function tells us if a number is safe or not. If it's a safe number, it returns true.

Safe integers are all whole numbers from -(2^53 - 1) to +(2^53 - 1).
This is safe: 9007199254740991. This is not safe: 9007199254740992.