JavaScript 是一门弱类型语言,其 Number 类型的数据在进行数值计算时存在精度丢失问题,因此在进行大数计算时,需要使用 BigInt 类型来保证计算精度。ES11 引入了 BigInt 类型,使得 JavaScript 可以进行更加精确的大数计算。
BigInt 类型
BigInt 类型是 JavaScript 中的一种新的基本数据类型,用于表示任意精度的整数。与 Number 类型不同,BigInt 类型没有固定的最大值,可以表示任意大的整数。BigInt 类型的值必须以 "n" 结尾,例如:
const a = 1234567890123456789012345678901234567890n; const b = 9876543210987654321098765432109876543210n;
BigInt 类型的运算
BigInt 类型支持基本的算术运算符(加、减、乘、除、余数)以及位运算符(按位与、按位或、按位异或、左移、右移)。BigInt 类型的运算符与 Number 类型的运算符类似,但需要注意的是,BigInt 类型的运算符只能与 BigInt 类型的值一起使用,不能与 Number 类型的值一起使用。例如:
// www.javascriptcn.com code example const a = 1234567890123456789012345678901234567890n; const b = 9876543210987654321098765432109876543210n; console.log(a + b); // 11111111111111111111111111111111111111100n console.log(a - b); // -8641975320864197532086419753208641975320n console.log(a * b); // 12193263113702179543195783263699732497976865580978951295424526341467633670239000n console.log(a / b); // 0n console.log(a % b); // 1234567890123456789012345678901234567890n console.log(a & b); // 1234567890123456789012345678901234567040n console.log(a | b); // 9876543210987654321098765432109876543350n console.log(a ^ b); // 9876543210987654321098765432109876541310n console.log(a << 2n); // 4938271560493827168904938271560493827160n console.log(a >> 2n); // 30864197530864197530864197530864197530n
BigInt 类型的转换
由于 BigInt 类型与 Number 类型不同,因此需要进行类型转换时需要注意。BigInt 类型可以通过 toString() 方法转换为字符串,也可以通过 Number()、parseInt()、parseFloat() 等方法将其转换为 Number 类型。需要注意的是,当 BigInt 类型的值超出 Number 类型的表示范围时,转换为 Number 类型会导致精度丢失。例如:
const a = 1234567890123456789012345678901234567890n; console.log(a.toString()); // "1234567890123456789012345678901234567890" console.log(Number(a)); // Uncaught RangeError: BigInt value is out of range in Number console.log(parseInt(a)); // Uncaught TypeError: Cannot convert a BigInt value to a number console.log(parseFloat(a)); // Uncaught TypeError: Cannot convert a BigInt value to a number
示例代码
下面是一个使用 BigInt 类型进行大数计算的示例代码:
// www.javascriptcn.com code example
function factorial(n) {
let result = 1n;
for (let i = 2n; i <= n; i++) {
result *= i;
}
return result;
}
console.log(factorial(100n)); // 93326215443944152681699238856266700490715968264381621468592963895217599993229915608941463976156518286253697920827223758251185210916864000000000000000000000000n以上代码计算了 100 的阶乘,结果为一个 158 位的大数。使用 Number 类型进行计算时,结果会出现精度丢失;而使用 BigInt 类型进行计算,则可以得到精确的结果。
指导意义
使用 BigInt 类型进行大数计算可以保证计算精度,特别是在进行高精度计算时,这种类型的使用显得尤为重要。在实际开发中,如果需要进行大数计算,建议使用 BigInt 类型来保证计算的准确性。
来源:JavaScript中文网 ,转载请注明来源 https://www.javascriptcn.com/post/67d0e979a941bf71341f26ab