Skip to content

Instantly share code, notes, and snippets.

@hfs
Created February 7, 2017 09:34
Show Gist options
  • Save hfs/7636e4d73e5d5143873f1eeae6bca02c to your computer and use it in GitHub Desktop.
Save hfs/7636e4d73e5d5143873f1eeae6bca02c to your computer and use it in GitHub Desktop.
Convert a byte count into a human readable, rounded String using kB, MB, etc. This is base-1000 and not base-1024.
/**
* Convert a byte count into a human readable, rounded String using kB, MB,
* etc. This is base-1000 and not base-1024.
*
* @param size number of bytes
* @return formatted String
*/
private static String readableSize(long size) {
if (size <= 0) {
return "0 B";
}
final String[] units = new String[] { "B", "kB", "MB", "GB", "TB", "EB" };
int digitGroups = (int) (Math.log10(size)/3);
return new DecimalFormat("#,##0.#").format(size/Math.pow(1000, digitGroups))
+ " " + units[digitGroups];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment