Skip to content

Instantly share code, notes, and snippets.

@lewdev
Last active March 3, 2022 03:18
Show Gist options
  • Select an option

  • Save lewdev/8ce517d7f7df487ab131cebc8f26e88f to your computer and use it in GitHub Desktop.

Select an option

Save lewdev/8ce517d7f7df487ab131cebc8f26e88f to your computer and use it in GitHub Desktop.
Convert bytes to formatted KB, MB, GB, TB, etc. in JavaScript.
<pre id=o></pre>
<script>
const UNITS = ",K,M,G,T,P".split(",");
const UNIT_SIZES = UNITS.reduce((prev, curr, i) => {
prev[curr] = Math.pow(1024, i);
return prev;
}, {});
const formatBytes = bytes => {
let size, unit;
for (let i = UNITS.length - 1; i >= 0; i--) {
unit = UNITS[i];
size = UNIT_SIZES[unit];
if (bytes >= size) {
return (Math.round(bytes / size * 100) / 100).toLocaleString("en-US") + ` ${unit}B`;
}
}
return 0;
};
//Demonstrate its usage:
const DEMO = [223,1234,1234567,1234567890,1234567890000,1234567890000000];
o.innerHTML = DEMO.map(a => `${formatBytes(a)} (${a.toLocaleString("en-US")} bytes)`).join("\n");
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment