Skip to content

Instantly share code, notes, and snippets.

@kindy
Created April 22, 2013 02:46
Show Gist options
  • Save kindy/5432112 to your computer and use it in GitHub Desktop.
Save kindy/5432112 to your computer and use it in GitHub Desktop.
/*
http://stackoverflow.com/questions/3758606/how-to-convert-byte-size-into-human-readable-format-in-java
public static String humanReadableByteCount(long bytes, boolean si) {
int unit = si ? 1000 : 1024;
if (bytes < unit) return bytes + " B";
int exp = (int) (Math.log(bytes) / Math.log(unit));
String pre = (si ? "kMGTPE" : "KMGTPE").charAt(exp-1) + (si ? "" : "i");
return String.format("%.1f %sB", bytes / Math.pow(unit, exp), pre);
}
*/
function humanReadableByteCount(bytes, si) {
var unit = si ? 1000 : 1024;
if (bytes < unit) {
return bytes + ' B';
}
var exp = Math.floor(Math.log(bytes) / Math.log(unit));
var hb = (si ? 'kMGTPE' : 'MKGTPE').charAt(exp - 1) + (si ? '' : 'i') + 'B';
var num = Math.round(bytes / Math.pow(unit, exp) * 10) / 10;
return num + ' ' + hb;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment