Created
September 28, 2017 04:57
-
-
Save vithalreddy/ba1d681990d7a837375cd9ee7c77c332 to your computer and use it in GitHub Desktop.
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 formatFileSize(bytes,decimalPoint) { | |
if(bytes == 0) return '0 Bytes'; | |
var k = 1000, | |
dm = decimalPoint || 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]; | |
} | |
//You only need to use the formatFileSize() function in JavaScript to convert file size units. | |
formatBytes(2000); // 2 KB | |
formatBytes(2234); // 2.23 KB | |
formatBytes(2234, 3); // 2.234 KB |
shouldn't the var k be 1024?
You cannot pass 0 for decimalPoint, because 0 || 2 in JavaScript is 2. Instead you can declare decimalPoint with a default value:
function formatFileSize(bytes,decimalPoint = 2) {
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for this snippet :)