Skip to content

Commit

Permalink
Fix denominator precision loss and remove unnecessary safe integer ch…
Browse files Browse the repository at this point in the history
…eck for fractional part
  • Loading branch information
yaooqinn committed Jan 14, 2025
1 parent 6ab280a commit 0e47fd2
Showing 1 changed file with 11 additions and 3 deletions.
14 changes: 11 additions & 3 deletions js/src/util/bn.ts
Original file line number Diff line number Diff line change
Expand Up @@ -91,15 +91,23 @@ export function bigNumToNumber<T extends BN<BigNumArray>>(bn: T, scale?: number)
number |= word * (BigInt(1) << BigInt(64 * i++));
}
}
if (typeof scale === 'number') {
const denominator = BigInt(10) ** BigInt(scale);
if (typeof scale === 'number' && scale > 0) {
const denominator = BigInt('1' + '0'.repeat(scale));
const quotient = number / denominator;
const remainder = number % denominator;
return bigIntToNumber(quotient) + Number('0.' + `${remainder}`.padStart(scale, '0'));
const fraction = Number('0.' + padStart(remainder.toString(), scale));
return bigIntToNumber(quotient) + fraction;
}
return bigIntToNumber(number);
}

function padStart(str: string, targetLength: number) {
while (str.length < targetLength) {
str = '0' + str;
}
return str;
}

/** @ignore */
export function bigNumToString<T extends BN<BigNumArray>>(a: T): string {
// use BigInt native implementation
Expand Down

0 comments on commit 0e47fd2

Please sign in to comment.