Format byte sizes
Convert raw byte counts into compact, human-readable binary units.MediumJavaScript Functions
30 min64.2% acceptance
Description
Implement formatBytes to display non-negative byte counts using B, KB, MB, GB, or TB. Values at unit boundaries must choose the larger unit, fractional values should have at most one decimal place, and zero must be rendered as 0 B.
Requirements
The solution exports a callable function named formatBytes.
Finite non-negative values are formatted with B, KB, MB, GB, or TB using 1024 as the unit base.
An exact 1024-based boundary is promoted to the next unit.
Non-integer unit values use at most one decimal digit and never include a trailing .0.
A value of zero returns exactly 0 B.
Negative, infinite, and NaN inputs throw a RangeError.
Fractional kilobytes
Input
formatBytes(1536)
Expected output
'1.5 KB'
Explanation
1536 bytes is one and a half binary kilobytes.
Exact megabyte
Input
formatBytes(1048576)
Expected output
'1 MB'
Constraints
Accept finite non-negative numbers onlyUse 1024 as the unit baseShow no more than one fractional digit and omit a trailing .0
Hints
Hint 1
Handle invalid values and zero before calculating a unit.
Hint 2
Use powers of 1024 to determine the largest supported unit that fits the value.
Hint 3
Round the scaled value to one decimal place, then format whole results without a decimal suffix.
numbersformattingedge cases