BigInt

作者: Fantast_d2be | 来源:发表于2020-06-09 09:35 被阅读0次

BigInt

BigInt 是一种内置对象,可以表示大于 2的53次方 的整数。而在Javascript中,Number 基本类型可以精确表示的最大整数是 2的53次方。BigInt 可以表示任意大的整数。

问题

JS 中的Number类型只能安全地表示-9007199254740991 (-(2^53-1)) 和9007199254740991(2^53-1)之间的整数,任何超出此范围的整数值都可能失去精度。

const maxInt = Number.MAX_SAFE_INTEGER;

console.log(maxInt + 1);        

console.log(maxInt + 2);     // → -9007199254740996

JS 提供Number.MAX_SAFE_INTEGER常量来表示 最大安全整数,Number.MIN_SAFE_INTEGER常量表示最小安全整数:

解决

const previousMaxSafe = BigInt(Number.MAX_SAFE_INTEGER);
// ↪ 9007199254740991n

const maxPlusOne = previousMaxSafe + 1n;
// ↪ 9007199254740992n
console.log(maxPlusOne);
const theFuture = previousMaxSafe + 2n;
// ↪ 9007199254740993n, this works now!
console.log(theFuture)

语法

BigInt(value);

或者在整数的末尾追加n即可

类型信息

typeof 1n === 'bigint'; // true
typeof BigInt('1') === 'bigint'; // true

比较

BigInt 和 Number 不是严格相等的,但是宽松相等的。

0n === 0
// ↪ false

0n == 0

Number 和 BigInt 可以进行比较。

1n < 2
// ↪ true

2n > 1
// ↪ true

2 > 2
// ↪ false

2n > 2
// ↪ false

2n >= 2
// ↪ true

注意点

25 / 10;      // → 2.5
25n / 10n;   

BigInt("10");    // → 10n
BigInt(10);      // → 10n
BigInt(true);    // → 1n

BigInt(10.2);     // → RangeError
BigInt(null);     // → TypeError
BigInt("abc");    // → SyntaxError

1n + 1

BigInt 不能与 Number类型互相运算

参考

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/BigInt

相关文章

  • BigInt

    BigInt BigInt 是一种内置对象,可以表示大于 2的53次方 的整数。而在Javascript中,Num...

  • PHP 疑难杂症

    PHP 使用unsigned bigint PHP 使用unsigned bigint作为主键时应该使用PHPx6...

  • int、bigint、smallint 和 tinyint

    int、bigint、smallint 和 tinyint 使用整数数据的精确数字数据类型。 bigint 从 -...

  • js数据类型BigInt

    BigInt数据类型的目的是比Number数据类型支持的范围更大的整数值。BigInt构造函数: Number类型...

  • 【Dart/Flutter】中对于BigInt的一些操作

    Dart中BigInt的基本计算函数 Dart中对于大数字只有一个BigInt,没有像Java中的BigDecim...

  • json-bigint

    https://github.com/sidorares/json-bigint[https://github.c...

  • 图书信息管理模块实现

    1.数据库t_book表,主键id为bigint类型,type_id为bigint类型(图书所属类别的id) 2....

  • 数据库

    id bigint(20) unsigned 20 0 N 主键

  • BigInteger实现&的位运算操作

    问题来源:下位机数据对接 数据库的数据类型为bigint和无符号bigInt分别对应java的Long类型和Big...

  • HiveSql

    -- 类型转换:cast SELECT CAST('00321' AS BIGINT) FROM table; -...

网友评论

      本文标题:BigInt

      本文链接:https://www.haomeiwen.com/subject/xtpgzhtx.html