Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions packages/shared/src/usageFormat.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import type { UsageSource } from "@t3tools/contracts";
import {
formatDateTimeShort,
formatHourShort,
formatPercent,
formatTokens,
makeWindow,
usageSourceMessages,
Expand Down Expand Up @@ -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");
Expand Down
3 changes: 3 additions & 0 deletions packages/shared/src/usageFormat.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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)}%`;
}

Expand Down
Loading