Format bytes as human-readable sizes
Format a byte count as a human-readable size, with a loop over binary units, and see where Intl.NumberFormat with the unit style differs. Node.js 18.
Showing 1536 as 1.5 KiB takes a logarithm, a unit table and a rounding step. The function below ran on Node.js 24, and one line of its output shows where the built-in unit formatter disagrees with it.
const units = ['B', 'KiB', 'MiB', 'GiB', 'TiB'];
function formatBytes(bytes, digits = 1) {
if (bytes === 0) return '0 B';
const power = Math.min(Math.floor(Math.log(Math.abs(bytes)) / Math.log(1024)), units.length - 1);
const value = bytes / 1024 ** power;
return `${Number.parseFloat(value.toFixed(digits))} ${units[power]}`;
}
console.log([0, 1023, 1024, 1536, 5_242_880, 1_073_741_824, 2 ** 50].map((n) => formatBytes(n)));
console.log(new Intl.NumberFormat('en', { style: 'unit', unit: 'megabyte', maximumFractionDigits: 1 }).format(5.24288));[
'0 B', '1023 B',
'1 KiB', '1.5 KiB',
'5 MiB', '1 GiB',
'1024 TiB'
]
5.2 MBThe power is floor(log(bytes) / log(1024)), capped at the last unit, so 1_073_741_824 becomes 1 GiB. parseFloat(value.toFixed(1)) trims the trailing zero, and 1024 prints 1 KiB and not 1.0 KiB. The last line uses Intl.NumberFormat with style: 'unit' and unit: 'megabyte', which formats a number with a localized unit name but does no conversion and counts in the units it is given, so 5.24288 prints 5.2 MB and it does not know that 5,242,880 bytes is 5 MiB. The unit identifiers are in the ECMA-402 specification for Intl.NumberFormat.
Pick one convention. KiB, MiB and GiB mean multiples of 1,024. The SI kB, MB and GB mean multiples of 1,000, and mixing them gives sizes that differ by about 7 percent at the gigabyte level. Operating systems disagree too, so say which one you use in the interface.