Skip to content

Instantly share code, notes, and snippets.

@skyler
Created June 3, 2010 16:38
Show Gist options
  • Save skyler/424115 to your computer and use it in GitHub Desktop.
Save skyler/424115 to your computer and use it in GitHub Desktop.
import java.text.DecimalFormat;
import java.text.NumberFormat;
public static String formatBytes(long numBytes)
{
NumberFormat formatter = new DecimalFormat("#.00");
StringBuffer buffer = new StringBuffer();
if (numBytes > 1024) {
if (numBytes >= 1073741824D) {
buffer.append(formatter.format((double) numBytes / 1073741824D)).append("GB");
} else if (numBytes >= 1048576D) {
buffer.append(formatter.format((double) numBytes / 1048576D)).append("MB");
} else {
buffer.append(formatter.format((double) numBytes / 1024D)).append("kB");
}
} else {
buffer.append(numBytes).append(" bytes"); // Looks better and is more familiar than abbreviation "B"
}
return buffer.toString();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment