BigInt modulo float

105 Views Asked by At

I would like to calculate the a bigint modulo a number (float)

As a % b will necessarily be lower than b, the result can be expressed as a number.

example: with 10 000 000 000 000 000 004 modulo 1.43
expected result: 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

how can i create a bigModulo function with this signature?

function bigModulo(numerator: bigint, denominator: number): number
1

There are 1 best solutions below

6
Knight Industries On

The calculation can be solved by converting it into a bigint-only problem, apply bigint-modulo and then convert it back to the original scale:

function bigModulo(numerator: bigint, denominator: number): number {
  if (!denominator) return NaN;
  let scale = 1;
  while (denominator % 1 !== 0) {
    numerator *= 10n;
    denominator *= 10;
    scale *= 10;
  }
  return Number(numerator % BigInt(denominator)) / scale;
}

bigModulo(10_000_000_000_000_000_004n, 1.43); //1.13