Skip to content

Instantly share code, notes, and snippets.

@gokhantaskan
Last active January 18, 2023 10:40
Show Gist options
  • Save gokhantaskan/b5aa55e60efe06ce42063298a8ecc3a2 to your computer and use it in GitHub Desktop.
Save gokhantaskan/b5aa55e60efe06ce42063298a8ecc3a2 to your computer and use it in GitHub Desktop.
Metamask style balance formatter
import { BigNumber } from "@ethersproject/bignumber";
import { formatUnits, parseUnits } from "@ethersproject/units";
/**
* @param balance Token balance in BigNumber format
* @param decimals Token decimals
* @param fixed The number of decimal places to show
* @returns string representation of the balance
*/
export function bigNumberToTrimmed(
balance: BigNumber,
decimals = 18,
fixed = 4
): string {
if (!(balance instanceof BigNumber)) {
throw new Error(
`"Invalid balance type: ${typeof balance}. Should be BigNumber.`
);
}
if (balance.isZero()) {
return "0";
} else if (
BigNumber.from(parseUnits(formatUnits("1", fixed), decimals)).gt(balance)
) {
return `< ${formatUnits("1", fixed)}`;
} else {
const [l, r] = formatUnits(balance.toString()).split(".");
return Intl.NumberFormat("en-US", {
minimumFractionDigits: 0,
maximumFractionDigits: fixed,
})
.format(
parseFloat(`${l}.${r?.slice(0, fixed + 1).replace(/0+$/, "") ?? 0}`)
)
.toString();
}
}
import { BigNumber } from "@ethersproject/bignumber";
import { describe, expect, it } from "vitest";
import { parseUnits, formatUnits } from "ethers/lib/utils";
import { bigNumberToTrimmed, hexToNumber, numberToHex } from "./format-balance";
describe("bigNumberToTrimmed", () => {
it("test cases", () => {
expect(bigNumberToTrimmed(BigNumber.from("0"))).toEqual("0");
expect(bigNumberToTrimmed(BigNumber.from("1"))).toEqual("< 0.0001");
expect(bigNumberToTrimmed(BigNumber.from("100000000000000"))).toEqual("0.0001");
expect(bigNumberToTrimmed(BigNumber.from("1000000000000000000"))).toEqual("1");
expect(bigNumberToTrimmed(BigNumber.from("1000000000000000000000"))).toEqual("1,000");
expect(bigNumberToTrimmed(BigNumber.from(parseUnits(formatUnits("123456789", 4), 18)))).toEqual("12,345.6789");
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment