BigInt 模浮点

问题描述 投票:0回答:1

我想计算 a

bigint
模 a
number
(浮点数)

由于

a % b
必然低于
b
,因此结果可以表示为
number

示例:10 000 000 000 000 000 004 模 1.43
预期结果:1.13

10_000_000_000_000_000_004 % 1.43
// 🙁 0.042653000061321444

10_000_000_000_000_000_004n % 1.43
// 🙁 TypeError: can't convert BigInt to number

如何使用此签名创建 bigModulo 函数?

function bigModulo(numerator: bigint, denominator: number): number
javascript modulo bigint
1个回答
0
投票

计算可以通过将其转换为仅限

bigint
的问题来解决,应用
bigint
模,然后将其转换回原始比例:

function bigModulo(numerator: bigint, denominator: number): number {
  const scale = 10 ** (String(denominator).split('.')[1] || '').length;
  const n1 = numerator * BigInt(scale);
  const d1 = BigInt(denominator * Number(scale));
  return Number(n1 % d1) / Number(scale);
}
© www.soinside.com 2019 - 2024. All rights reserved.