Created
March 19, 2013 03:05
-
Star
(106)
You must be signed in to star a gist -
Fork
(25)
You must be signed in to fork a gist
-
-
Save lanqy/5193417 to your computer and use it in GitHub Desktop.
JavaScript To Convert Bytes To MB, KB, Etc
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
| // from http://scratch99.com/web-development/javascript/convert-bytes-to-mb-kb/ | |
| function bytesToSize(bytes) { | |
| var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB']; | |
| if (bytes == 0) return 'n/a'; | |
| var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024))); | |
| if (i == 0) return bytes + ' ' + sizes[i]; | |
| return (bytes / Math.pow(1024, i)).toFixed(1) + ' ' + sizes[i]; | |
| }; |
@weroro-sk Good point, thanks for sharing! I gave it a try my way just for fun. The code uses Intl.PluralRules, but the whole function is more robust now. Feel free to check it out.
Shouldn't 999999999 return 1 GB and not 1000 MB, since 1000000000 returns 1 GB.
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:
const size = new SmartUnit(['B', 'KB', 'MB', 'GB', 'TB'], { baseDigit: 1024 });
size.format(1234); // "1.21KB"
size.parse('1.5GB'); // 1610612736And 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:
const time = new SmartUnit(['ms', 1000, 's', 60, 'm', 60, 'h']);
time.format(5400000); // "1.5h"
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@gynekolog I implemented a simple word declension for the word "byte".
Example:
I'm from Slovakia, so in my case it would be: