diff --git a/web/src/lib/size.test.ts b/web/src/lib/size.test.ts index 82494e4..6efea56 100644 --- a/web/src/lib/size.test.ts +++ b/web/src/lib/size.test.ts @@ -6,6 +6,9 @@ test.each([ [999, 'en', '999 B'], [1000, 'en', '1 kB'], [1_500, 'en', '1.5 kB'], + [999_949, 'en', '999.9 kB'], + [999_950, 'en', '1 MB'], + [999_999_999, 'en', '1 GB'], [42_000_000, 'en', '42 MB'], [4_320_000_000, 'en', '4.3 GB'], [4_320_000_000, 'it', '4,3 GB'], diff --git a/web/src/lib/size.ts b/web/src/lib/size.ts index 8c183a5..f388b90 100644 --- a/web/src/lib/size.ts +++ b/web/src/lib/size.ts @@ -3,8 +3,10 @@ const UNITS = ['B', 'kB', 'MB', 'GB', 'TB'] /** A size in bytes as people read it ("4.3 GB"): units of 1000, one decimal at most, the number in the reader's language. */ export function formatBytes(bytes: number, language?: string): string { if (!Number.isFinite(bytes) || bytes <= 0) return '0 B' - const unit = Math.min(Math.floor(Math.log10(bytes) / 3), UNITS.length - 1) - const value = bytes / 1000 ** unit + let unit = Math.min(Math.floor(Math.log10(bytes) / 3), UNITS.length - 1) + // What is shown is rounded, so 999 950 bytes would read "1000 kB": it is "1 MB". + const shown = (u: number) => (u === 0 ? Math.round(bytes) : Math.round((bytes / 1000 ** u) * 10) / 10) + if (shown(unit) >= 1000 && unit < UNITS.length - 1) unit++ const digits = unit === 0 ? 0 : 1 - return `${new Intl.NumberFormat(language, { maximumFractionDigits: digits }).format(value)} ${UNITS[unit]}` + return `${new Intl.NumberFormat(language, { maximumFractionDigits: digits }).format(bytes / 1000 ** unit)} ${UNITS[unit]}` }