diff --git a/packages/shared/src/usageFormat.test.ts b/packages/shared/src/usageFormat.test.ts index 778877a202616..fe882bfa3f116 100644 --- a/packages/shared/src/usageFormat.test.ts +++ b/packages/shared/src/usageFormat.test.ts @@ -5,6 +5,7 @@ import type { UsageSource } from "@t3tools/contracts"; import { formatDateTimeShort, formatHourShort, + formatPercent, formatTokens, makeWindow, usageSourceMessages, @@ -236,6 +237,14 @@ describe("hourly usage formatting", () => { }); }); +describe("percent formatting", () => { + it("keeps a share short of the whole below 100%", () => { + expect(formatPercent(0.9996)).toBe(">99.9%"); + expect(formatPercent(0.999)).toBe("99.9%"); + expect(formatPercent(1)).toBe("100.0%"); + }); +}); + describe("token formatting", () => { it("moves to the next unit when rounding reaches it", () => { expect(formatTokens(999_999)).toBe("1M"); diff --git a/packages/shared/src/usageFormat.ts b/packages/shared/src/usageFormat.ts index 36c560cf54dce..973a72bb445c4 100644 --- a/packages/shared/src/usageFormat.ts +++ b/packages/shared/src/usageFormat.ts @@ -115,6 +115,9 @@ export function formatPercent(share: number, digits = 1): string { const percent = share * 100; const smallest = 10 ** -digits; if (percent > 0 && percent < smallest) return `<${smallest.toFixed(digits)}%`; + // A share short of the whole must not round up to 100%, as a nonzero one must not read 0%. + const largest = 100 - smallest; + if (percent < 100 && percent > largest) return `>${largest.toFixed(digits)}%`; return `${percent.toFixed(digits)}%`; }