Created
October 10, 2012 16:02
-
-
Save rderoldan1/3866561 to your computer and use it in GitHub Desktop.
Method to format long numbers in GB, MB and KB
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output example of formater1.java