sonda/web/src/lib/size.ts
tgiachi 51e949ae2b fix(web): a size that rounds up to the next unit is written in that unit
999 950 bytes read "1,000 kB" instead of "1 MB".
2026-11-12 17:18:51 +01:00

12 lines
789 B
TypeScript

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'
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(bytes / 1000 ** unit)} ${UNITS[unit]}`
}