Last active
June 16, 2024 04:50
-
-
Save huynhducduy/df6b8eafabbd4f9df64282ae7276a2a9 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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}`; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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