Created
September 27, 2017 11:57
-
-
Save zentala/1e6f72438796d74531803cc3833c039c to your computer and use it in GitHub Desktop.
Convert size in bytes to human readable format (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
| function formatBytes(bytes,decimals) { | |
| if(bytes == 0) return '0 Bytes'; | |
| var k = 1024, | |
| dm = decimals || 2, | |
| sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'], | |
| i = Math.floor(Math.log(bytes) / Math.log(k)); | |
| return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i]; | |
| } | |
| // Usage: | |
| // formatBytes(bytes,decimals) | |
| formatBytes(1024); // 1 KB | |
| formatBytes('1024'); // 1 KB | |
| formatBytes(1234); // 1.21 KB | |
| formatBytes(1234, 3); // 1.205 KB |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
If you find yourself tweaking this snippet frequently, smart-unit might be worth a look — it handles this out of the box with configurable decimal places, TypeScript support, and bidirectional
format/parse:And bytes formatting is just one use case — the same API works for any unit system with variable ratios, like time, length, frequency, or anything custom: