ㄧ日客家话:中文:去哪里 客语:诶 ㄏㄧ 赖 诶
BigInt对数学、金融、科学来说是很重要的,因为当number大於某范围会有精确度问题,故会将值当作string处理,但BigInt是可以表示为numeric values
JavaScript 是双精度浮点数
会留一个位置给科学记好左边的1
所以是2的53次方
Number最大安全表示:=9,007,199,254,740,991
9,007,199,254,740,991是最大且安全的整数
console.log(9007199254740991 + 1 === 9007199254740991 + 2);// true
console.log(9007199254740991n + 1n === 9007199254740991n + 2n);// false
要安全地使用大於此值的整数,您需要使用BigInt。
ECMA:
BigInt literals
:数字+小写n (预设十进位)ex:10n也可以使用其他进位:
0b(二进位):0b11n
0o(八进位):0o17n
base10(十进位):10n
0x(十六进位):0x1fn
BigInt()
将数字或字串转为BigInt值console.log(Number.MAX_SAFE_INTEGER);//9007199254740991(2 ** 53 - 1) js最安全大值
console.log(Number.MIN_SAFE_INTEGER);//-9007199254740991(-(2 ** 53 - 1)). js最小安全值
console.log(BigInt(Number.MAX_SAFE_INTEGER));
//9007199254740991n
console.log(BigInt(Number.MIN_SAFE_INTEGER));
//-9007199254740991n
当使用浮点数则无法使用
console.log(BigInt(100.6));
//RangeError: The number 100.6 cannot be converted to a BigInt because it is not an integer
可以进行算数运算 : +、-、*、/、%、 **
const value = 300n + 200n;
console.log(value);//500n
const a = BigInt(300);
const b = BigInt(200);
console.log(a + b)//500n
console.log(a - b)//100n
console.log(a % b)//100n
那进行除法运算呢?余数会直接舍弃
const a = BigInt(300);
const b = BigInt(200);
console.log(a / b);//1n
数字和bigint不能混用
let bigint = 10n;
let number = 100;
console.log(bigint + number);//TypeError: Cannot mix BigInt and other types, use explicit conversions
只能Bigint转成数字或number转成Bigint
console.log(bigint + BigInt(number));//110n
console.log(Number(bigint) + number);//110
无法使用+来转型别
let bigint = 1n;
console.log(+bigint);
//TypeError: Cannot convert a BigInt value to a number
//无法转译
console.log(1 == 1n);
//true
console.log(1 === 1n);
//false
运算2的53次方-1以上时只使用BigInt
当Number超过2的53次方-1以上的数转成BigInt也会失准
b = BigInt(9007199254740993)
console.log(b)//9007199254740992n
console.log(Boolean(0n)); //false
v8使用Arbitrary-precision arithmetic 解决Number浮点精度问题
BigInt 相乘实作方式
有兴趣可以到V8官网研究
最後大家可以斟酌何时使用number和BigInt
在tc39/proposal-bigint 说
Don't break math
The semantics of all operators should ideally be based on some mathematical first principles, to match developer expectations. The division and modulo operators are based on conventions from other programming languages for integers.
IEEE-754 References
V8
知乎:BigInt:JavaScript 中的任意精度整数
BigInt, arbitrary precision integers in JavaScript
mdn
js大全
tc39-proposal-bigint
前言 在过去介绍过的工具里,有一些是收集资讯用的,像是作业系统、软件版本等资讯,找到这些资讯後,可能...
Html的标签有许多种,我们不需要一开始就把所有的背下脑海里,而是可以透过反覆使用,将常用的标签用法...
上一篇介绍了 plugin 是什麽、如何安装使用,以及推荐的插件。今天我们实际透过这些插件实作一个简...
为了在後续章节里示范 TeamCity 可以怎麽协助我们建置专案及一系列的自动化,我们需要有一个可以...
在建置ELB前,我们先多做一个步骤去完成昨天URL重写的步骤。 步骤 10 更改S3的bucket ...