Skip to content

Instantly share code, notes, and snippets.

@ali-master
Created April 9, 2024 21:37
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ali-master/5e010f41b711b6de509798a69a8b74aa to your computer and use it in GitHub Desktop.
Save ali-master/5e010f41b711b6de509798a69a8b74aa to your computer and use it in GitHub Desktop.
Javscript Number fixed point
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