Skip to content

Instantly share code, notes, and snippets.

@huynhducduy
Last active June 16, 2024 04:50
Show Gist options
  • Save huynhducduy/df6b8eafabbd4f9df64282ae7276a2a9 to your computer and use it in GitHub Desktop.
Save huynhducduy/df6b8eafabbd4f9df64282ae7276a2a9 to your computer and use it in GitHub Desktop.
function bigIntToFloatString(value: bigint, decimalPlaces: number) {
if (typeof decimalPlaces !== 'number' || decimalPlaces < 0 || !Number.isInteger(decimalPlaces)) {
throw new TypeError('The second argument must be a non-negative integer');
}
const divisor = BigInt(10 ** decimalPlaces); // 1e{decimalPlaces}
const integerPart = value / divisor;
const fractionalPart = value % divisor;
const integerString = integerPart.toString();
const fractionalString = fractionalPart.toString().padStart(decimalPlaces, '0');
return `${integerString}.${fractionalString}`;
}
function floatStringToBigInt(floatString: string, decimalPlaces: number) {
if (typeof decimalPlaces !== 'number' || decimalPlaces < 0 || !Number.isInteger(decimalPlaces)) {
throw new TypeError('The second argument must be a non-negative integer');
}
const [integerPart, fractionalPart = ''] = floatString.split('.');
const combinedString = integerPart + fractionalPart.padEnd(decimalPlaces, '0');
return BigInt(combinedString);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment