Created
April 9, 2024 21:37
-
-
Save ali-master/5e010f41b711b6de509798a69a8b74aa to your computer and use it in GitHub Desktop.
Javscript Number fixed point
This file contains hidden or 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
export function formatFixedPoint(val: bigint, decimals = 18): string { | |
const l = val / 10n ** BigInt(decimals); | |
const r = val % 10n ** BigInt(decimals); | |
if (r === 0n) { | |
return l.toString(); | |
} | |
return `${l}.${r.toString().padStart(decimals, "0").replace(/0*$/, "")}`; | |
} | |
export function parseFixedPoint(ori: string | number, decimals = 18): bigint { | |
const [l, r] = ori.toString().split("."); | |
const lVal = BigInt(l) * 10n ** BigInt(decimals); | |
if (r === undefined) { | |
return lVal; | |
} | |
return lVal + BigInt(r.padEnd(decimals, "0").replace(/^0*/, "")); | |
} | |
export class FixedPoint { | |
public static readonly Zero = 0n; | |
public static readonly One = parseFixedPoint("1"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment