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".
This commit is contained in:
parent
62816909b2
commit
51e949ae2b
2 changed files with 8 additions and 3 deletions
|
|
@ -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'],
|
||||
|
|
|
|||
|
|
@ -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]}`
|
||||
}
|
||||
|
|
|
|||
Loading…
Reference in a new issue