12 lines
789 B
TypeScript
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]}`
|
|
}
|