如何在jQuery中实现BigInt与Number的乘法运算?
正确实现BigInt与Number的乘法操作
当前代码直接将字符串类型的countLicenses与Number相乘时,JS会自动把字符串转为Number,但如果这个字符串是超出**Number安全范围(2^53-1)**的大整数,会丢失精度。要基于BigInt完成高精度乘法,按以下步骤修改:
- 将字符串类型的
countLicenses转为BigInt:用BigInt()构造函数,确保输入是合法的整数字符串 - 将Number类型的
price10也转为BigInt(或直接用BigInt字面量10n),因为BigInt与Number不能直接运算 - 相乘后把结果转为字符串,避免显示时带BigInt的后缀
n
修改后的代码:
let price10 = 10; let countLicenses = $(this).find('.field').val(); // 字符串类型的整数 // 转换为BigInt,若输入不是合法整数会抛出错误,可按需添加校验逻辑 const countBigInt = BigInt(countLicenses); const priceBigInt = BigInt(price10); const resultPrice = countBigInt * priceBigInt; // 将BigInt结果转为字符串后渲染 $(this).find('.result').text(String(resultPrice));
可选的输入校验
如果需要处理用户输入非法值的情况,可添加简单校验:
let countLicenses = $(this).find('.field').val(); // 校验输入是否为纯数字字符串 if (/^\d+$/.test(countLicenses)) { const countBigInt = BigInt(countLicenses); const priceBigInt = BigInt(10); const resultPrice = countBigInt * priceBigInt; $(this).find('.result').text(String(resultPrice)); } else { $(this).find('.result').text('请输入合法整数'); }
内容的提问来源于stack exchange,提问作者Azizxon Zufarov
相关产品推荐
相关产品推荐

