Skip to content
Open
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
14 changes: 14 additions & 0 deletions packages/shared/src/usageFormat.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,23 @@ import {
formatHourShort,
formatPercent,
formatRelativeHourShort,
formatTokens,
makeWindow,
} from "./usageFormat.ts";

describe("formatTokens", () => {
it("promotes a rounded-up boundary into the next unit instead of printing 1000K", () => {
expect(formatTokens(999_499)).toBe("999K");
expect(formatTokens(999_500)).toBe("1M");
expect(formatTokens(999_999)).toBe("1M");
expect(formatTokens(999_999_999)).toBe("1B");
expect(formatTokens(1_500_000)).toBe("1.50M");
expect(formatTokens(-999_500)).toBe("-1M");
expect(formatTokens(804)).toBe("804");
expect(formatTokens(76_700_000)).toBe("76.7M");
});
});

describe("formatPercent", () => {
it("distinguishes a small positive share from zero", () => {
expect(formatPercent(0)).toBe("0.0%");
Expand Down
23 changes: 19 additions & 4 deletions packages/shared/src/usageFormat.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,16 +25,31 @@ export function formatCount(value: number): string {
return INTEGER.format(Math.round(value));
}

const TOKEN_UNITS = [
[1e12, "T"],
[1e9, "B"],
[1e6, "M"],
[1e3, "K"],
] as const;

/**
* Compacts a token count to three significant figures with a unit suffix, so
* columns of numbers line up at a glance (`19.9B`, `76.7M`, `804K`).
*/
export function formatTokens(value: number): string {
const abs = Math.abs(value);
if (abs >= 1e12) return `${trim(value / 1e12)}T`;
if (abs >= 1e9) return `${trim(value / 1e9)}B`;
if (abs >= 1e6) return `${trim(value / 1e6)}M`;
if (abs >= 1e3) return `${trim(value / 1e3)}K`;
for (let i = 0; i < TOKEN_UNITS.length; i++) {
const [scale, suffix] = TOKEN_UNITS[i];
if (abs < scale) continue;
const text = trim(value / scale);
// trim() rounds: 999.5K would otherwise print "1000K". Promote a
// rounded-up boundary into the next unit so columns stay aligned.
if ((text === "1000" || text === "-1000") && i > 0) {
const [nextScale, nextSuffix] = TOKEN_UNITS[i - 1];
return `${trim(value / nextScale)}${nextSuffix}`;
}
return `${text}${suffix}`;
}
return INTEGER.format(Math.round(value));
}

Expand Down
Loading