Total Pageviews

Wednesday, November 16, 2011

Convert byte size into human readable format in Java ( and GWT )

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);
}
Java GWT:
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 toFixed(bytes / Math.pow(unit, exp), 1) + " " + pre
    + "B";
}
public static native String toFixed(double d, int fixed)/*-{
  return d.toFixed(fixed);
}-*/;

Orgin from here

1 comment: