Last active
March 3, 2022 03:18
-
-
Save lewdev/8ce517d7f7df487ab131cebc8f26e88f to your computer and use it in GitHub Desktop.
Convert bytes to formatted KB, MB, GB, TB, etc. in JavaScript.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <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