Skip to content

Instantly share code, notes, and snippets.

@rderoldan1
Created October 10, 2012 16:02
Show Gist options
  • Save rderoldan1/3866561 to your computer and use it in GitHub Desktop.
Save rderoldan1/3866561 to your computer and use it in GitHub Desktop.
Method to format long numbers in GB, MB and KB
private String format_long(long number){
String formatted;
if (number > 1000000000) {
String re = "^(.*)\\d{9}$";
Matcher m = Pattern.compile(re).matcher(Long.toString (number));
if (m.find()) {
formatted = m.group(1) + " Gb";
} else {
formatted = "0";
}
} else if (number > 1000000) {
String re = "^(.*)\\d{6}$";
Matcher m = Pattern.compile(re).matcher(Long.toString (number));
if (m.find()) {
formatted = m.group(1) + " Mb";
} else {
formatted = "0";
}
} else if (number > 1000) {
String re = "^(.*)\\d{3}$";
Matcher m = Pattern.compile(re).matcher(Long.toString (number));
if (m.find()) {
formatted = m.group(1) + " Kb";
} else {
formatted = "0";
}
} else {
formatted = Long.toString (number) + " bytes";
}
return (formatted);
}
public String readableFileSize(long size) {
if(size <= 0) return "0";
final String[] units = new String[] { "B", "KB", "MB", "GB", "TB", "PB", "EB" };
int digitGroups = (int) (Math.log10(size)/Math.log10(1024));
String result = null;
result = new DecimalFormat("#,##0.#").format(size/Math.pow(1024, digitGroups)) + " " + units[digitGroups];
return result;
}
@rderoldan1
Copy link
Author

Output example of formater1.java

142161739776      -->      132,4 GB
1353720004608      -->      1,2 TB
80701554688      -->      75,2 GB
299842404352      -->      279,2 GB
168587952128      -->      157 GB
749740228608      -->      698,2 GB
36377198592      -->      33,9 GB
49928994816      -->      46,5 GB
46920630272      -->      43,7 GB
249913409536      -->      232,8 GB
171773526016      -->      160 GB
1722550321152      -->      1,6 TB

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment