Skip to content
14 changes: 14 additions & 0 deletions src/main/wallet-balances.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,20 @@ describe("formatTokenBalanceFull", () => {
it("formats fractions with 4 significant digits", () => {
expect(formatTokenBalanceFull("123400000000000000", 18)).toBe("0.1234");
});

it("trims zeros exposed by the 4-digit cut", () => {
// 1.20001 tokens → "1.2" not "1.2000"
expect(formatTokenBalanceFull("1200010000000000000", 18)).toBe("1.2");
});

it("drops the fraction when the cut leaves only zeros", () => {
expect(formatTokenBalanceFull("1000010000000000000", 18)).toBe("1");
});

it("trims zeros exposed by the cut below 1", () => {
// 0.0001200005 tokens → "0.00012"
expect(formatTokenBalanceFull("120000500000000", 18)).toBe("0.00012");
});
});

describe("formatTokenBalance precision for huge balances", () => {
Expand Down
6 changes: 4 additions & 2 deletions src/shared/tokens.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,13 +68,15 @@ export function formatTokenBalanceFull(raw: string, decimals: number): string {
const trimmedFrac = fractionalPart.replace(/0+$/, "");

if (integerPart !== "0") {
const capped = trimmedFrac.slice(0, 4);
// Truncation can expose trailing zeros (1.20001 → "2000").
const capped = trimmedFrac.slice(0, 4).replace(/0+$/, "");
return capped ? `${integerPart}.${capped}` : integerPart;
}

if (firstNonZero >= 4) return "< 0.0001";
const significantDigits = trimmedFrac.slice(firstNonZero);
const visible = significantDigits.slice(0, 4);
// The first significant digit is nonzero, so trimming keeps at least one.
const visible = significantDigits.slice(0, 4).replace(/0+$/, "");
return `0.${"0".repeat(firstNonZero)}${visible}`;
}

Expand Down
Loading