Readablize Bytes

by findango

HTML

<script>
function stringify(value) {
	return typeof value === 'object'
    	? JSON.stringify(value, null, 2)
        : value;
}

function log() {
    var args = Array.prototype.slice.call(arguments, 0);
    document.getElementById('output').innerHTML += args.map(stringify).join(" ") + "\n";
}
</script>

<pre id="output"></pre>

JavaScript

function readablizeBytes(bytes) {
    var s = ['bytes', 'kB', 'MB', 'GB', 'TB', 'PB'];
    var e = Math.floor(Math.log(bytes) / Math.log(1024));
    return (bytes / Math.pow(1024, e)).toFixed(2) + " " + s[e];
}

log(readablizeBytes(1000))
log(readablizeBytes(3000))
log(readablizeBytes(12000))
log(readablizeBytes(10000000))
log(readablizeBytes(10000000000))