Created
October 16, 2017 18:02
-
-
Save Zetaphor/d0c0a40f42a54b45e7190d764901aba3 to your computer and use it in GitHub Desktop.
Format byte string to human readable label
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
// ** Demo code ** | |
var p = document.querySelector('p'), | |
input = document.querySelector('input'); | |
function setText(v){ | |
p.innerHTML = formatBytes(v); | |
} | |
// bind 'input' event | |
input.addEventListener('input', function(){ | |
setText( this.value ) | |
}) | |
// set initial text | |
setText(input.value); | |
<input type="text" value="1000"> | |
<p></p> |
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]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment