Article From:

JavaScriptThe basic data class, Number, is a double precision floating-point number, and the maximum security scope it can represent is positive and negative 9007199254740991, that is, the 53 subtraction of 2, and input the Number.MAX_SAFE_INTEGER in the browser console, respectively.Number.MIN_SAFE_INTEGER can check the corresponding maximum / minimum values.

const max = Number.MAX_SAFE_INTEGER;
    // → 9_007_199_254_740_991
    // Note: for ease of reading, I use the underscore as a separator to group these numbers into 1000 digits. The digital text separator proposal is correct for common JavaScript numeric characters.

By adding this maximum value, we can get the expected results.

max + 1;
// → 9_007_199_254_740_992 ✅

However, if we increase it again, the result can no longer be fully expressed as JavaScript.Number

max + 2;
// → 9_007_199_254_740_992 ❌

We’ll find that the results of max+1 and max+2 are the same.As long as we get this particular value in JavaScript, we can not judge whether it is accurate or not.An integer outside the range of the security integer (that is, fromNumber.MIN_SAFE_INTEGERreachNumber.MAX_SAFE_INTEGER)AAny calculationThe accuracy may be lost.For this reason, we can only rely on the numerical value in the security range.


BigIntIt is a new primitive type in JavaScript, which can be used.Arbitrary precisionRepresentation of integersUseBigInt,Even beyond JavaScriptNumber The security integer restriction can also safely store and manipulate large integers.

chrome 67+Start supporting BigInt. All demo in this article is based on chrome 67.

To create aBigInt,Add the N suffix after the number,For example,123Become123nOverall situationBigInt(number)The function can be used to convert NumberbecomeBigIntLet me put it another way,BigInt(123) === 123nLet’s use these two technologies to solve the problems we encountered before:

BigInt(Number.MAX_SAFE_INTEGER) + 2n;
// → 9_007_199_254_740_993n ✅

We will be twoNumber Multiplying

1234567890123456789 * 123;
// → 151851850485185200000 ❌

Look at the two numbers above, the end is 9 and 3, 9*3=27, but the result is 000 at the end, obviously wrong.Let’s use itBigIntInstead of:

1234567890123456789n * 123n;
// → 151851850485185185047n ✅

This time we got the right result.

Number Security integer constraintsNot applicable toBigIntTherefore,BigIntWe can perform the correct integer operation without worrying about losing accuracy.

BigIntIt is a primitive type in the JavaScript language.Therefore, it can be usedtypeofOperatorThis type is detected

typeof 123;
// → 'number'
typeof 123n;
// → 'bigint'

becauseBigIntsIt’s a separate type, so aBigIntIt’s never equal to aNumber,For example42n !== 42To compare aBigIntAnd aNumber,It will be before the comparisonOneConvert to another type or use abstract equal (==):

42n === BigInt(42);
// → true
42n == 42;
// → true

When forced to be Boolean (useif&&||,orBoolean(int)),BigIntThe same logical transformation as Number

if (0n) {
} else {
// → logs 'else', because `0n` is falsy.


BigIntSupport for the most common operators, the two element operators +, -, *, * *, and / or% are working normally, bitwise operation.|&, <<>>It's the same as Number.

(7 + 6 - 5) * 4 ** 3 / 2 % 3;
// → 1
(7n + 6n - 5n) * 4n ** 3n / 2n % 3n;
// → 1n

Unary operator-Can be used to represent a negative valueBigInt,for example-42nOne dollar+yesNot supported because it destroys asm.js code in asm.js.+xAlways throw outAbnormal.

Another problem is that it is not allowed inBigIntandNumber Mixed operation。Have a lookThis example:

BigInt(Number.MAX_SAFE_INTEGER) + 2.5;
// → ?? 🤔

What should be the result?There is no good answer here.BigIntCan’t represent a decimal, andNumberCannot expressBigIntA number that goes beyond the limit of the security integer.Therefore,BigIntandNumber BetweenAMixed operationcauseTypeErrorAbnormal.

The only exception to this rule is the comparison operator, for example.===(As mentioned earlier)<,also>=– Because they return to Boolean values, there is no risk of accuracy loss.

1 + 1n;
// → TypeError
123 < 124n;
// → true


Overall situationBigIntConstructor and constructorNumberSimilar:Convert its parameters toBigInt(As mentioned earlier).If the conversion fails, it throws oneSyntaxErrorOrRangeErrorAbnormal.

// → 123n
// → RangeError
// → SyntaxError

The two library functions will be enabledBigIntvalueencapsulationFor signed or unsigned integers, they are limited to specific digits.BigInt.asIntN(width, value)Take oneBigIntvaluePackingFor onewidth-digitBinary signed integers, and willBigInt.asUintN(width, value)OneBigIntvaluePackingFor onewidth-digitA binary unsigned integer.For example, if you are executing 64 bit arithmetic, you can use these API to maintain an appropriate range:

// Highest possible BigInt value that can be represented as a
// signed 64-bit integer.
const max = 2n ** (64n - 1n) - 1n;
BigInt.asIntN(64, max);
→ 9223372036854775807n
BigInt.asIntN(64, max + 1n);
// → -9223372036854775808n
//   ^ negative because of overflow

Please be careful, as long as we pass itBigIntMore than 64 integer values (for example, the absolute value is 63 bit + symbol is 1 bits).,There will be a spillover

BigIntIt can accurately represent 64 bit signed and unsigned integers, which are often used in other programming languages.Two new types of array style,BigInt64ArrayAndBigUint64ArrayIt is easier to effectively represent and manipulate the list of these values:

const view = new BigInt64Array(4);
// → [0n, 0n, 0n, 0n]
// → 4
// → 0n
view[0] = 42n;
// → 42n

BigInt64ArrayMake sure that its value is 64 bits.

// Highest possible BigInt value that can be represented as a
// signed 64-bit integer.
const max = 2n ** (64n - 1n) - 1n;
view[0] = max;
// → 9_223_372_036_854_775_807n
view[0] = max + 1n;
// → -9_223_372_036_854_775_808n
//   ^ negative because of overflow

BigUint64ArrayEnsure that these values are64The position is unsigned.


Leave a Reply

Your email address will not be published. Required fields are marked *