diff --git a/packages/cli/src/ui/utils/formatters.test.ts b/packages/cli/src/ui/utils/formatters.test.ts index d9094365fe8..61d5328c009 100644 --- a/packages/cli/src/ui/utils/formatters.test.ts +++ b/packages/cli/src/ui/utils/formatters.test.ts @@ -106,6 +106,21 @@ describe('formatters', () => { ); }); + it('should round milliseconds before picking the unit', () => { + expect(formatDuration(999.4)).toBe('999ms'); + expect(formatDuration(999.5)).toBe('1.0s'); + }); + + it('should round seconds before picking the unit', () => { + expect(formatDuration(59949)).toBe('59.9s'); + expect(formatDuration(59950)).toBe('1m'); + expect(formatDuration(59999)).toBe('1m'); + }); + + it('should round up to the hour', () => { + expect(formatDuration(3599999)).toBe('1h'); + }); + it('should handle negative durations', () => { expect(formatDuration(-100)).toBe('0s'); }); diff --git a/packages/cli/src/ui/utils/formatters.ts b/packages/cli/src/ui/utils/formatters.ts index 5a3f926dbe8..a7d8ec934b9 100644 --- a/packages/cli/src/ui/utils/formatters.ts +++ b/packages/cli/src/ui/utils/formatters.ts @@ -31,19 +31,22 @@ export const formatDuration = (milliseconds: number): string => { return '0s'; } - if (milliseconds < 1000) { - return `${Math.round(milliseconds)}ms`; + const roundedMs = Math.round(milliseconds); + if (roundedMs < 1000) { + return `${roundedMs}ms`; } - const totalSeconds = milliseconds / 1000; - - if (totalSeconds < 60) { - return `${totalSeconds.toFixed(1)}s`; + // Round to the displayed precision before picking a unit so a value just + // under a boundary does not round up into the next unit's range. + const tenthsOfSecond = Math.round(milliseconds / 100); + if (tenthsOfSecond < 600) { + return `${(tenthsOfSecond / 10).toFixed(1)}s`; } + const totalSeconds = Math.round(milliseconds / 1000); const hours = Math.floor(totalSeconds / 3600); const minutes = Math.floor((totalSeconds % 3600) / 60); - const seconds = Math.floor(totalSeconds % 60); + const seconds = totalSeconds % 60; const parts: string[] = [];