Skip to content

Instantly share code, notes, and snippets.

@rodrigopolo
Last active October 14, 2015 16:18
Show Gist options
  • Save rodrigopolo/7bf2a132f9ea018a26b7 to your computer and use it in GitHub Desktop.
Save rodrigopolo/7bf2a132f9ea018a26b7 to your computer and use it in GitHub Desktop.
Human readable bytes size in JavaScript
function formatSize(bytes, si) {
var unit = si ? 1000 : 1024;
if (bytes < unit) return (bytes % 1 === 0 ? bytes : bytes.toFixed(2)) + "B";
var exp = parseInt(Math.log(bytes) / Math.log(unit));
console.log(exp)
var pre = (si ? "kMGTPE" : "KMGTPE")[exp-1] + (si ? "" : "i")+'B';
var n = bytes / Math.pow(unit, exp);
return (n % 1 === 0 ? n : n.toFixed(2))+pre;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment