Skip to content

Instantly share code, notes, and snippets.

@Zetaphor
Created October 16, 2017 18:02
Show Gist options
  • Save Zetaphor/d0c0a40f42a54b45e7190d764901aba3 to your computer and use it in GitHub Desktop.
Save Zetaphor/d0c0a40f42a54b45e7190d764901aba3 to your computer and use it in GitHub Desktop.
Format byte string to human readable label
// ** 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>
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