You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 05:21:14