public class beautifySizeUtil {
public static String beautifySize(double size) {
if (size <= 0) return "0";
final String[] units = new String[]{"B", "KB", "MB", "GB", "TB"};
int digitGroups = (int) (Math.log10(size) / Math.log10(1024));
return new DecimalFormat("#,##0.#").format(size / Math.pow(1024, digitGroups)) + "" + units[digitGroups];
}
public static String beautifySize(long size) {
if (size <= 0) return "0";
final String[] units = new String[]{"B", "KB", "MB", "GB", "TB"};
int digitGroups = (int) (Math.log10(size) / Math.log10(1024));
return new DecimalFormat("#,##0.#").format(size / Math.pow(1024, digitGroups)) + "" + units[digitGroups];
}
//返回该B对应的美化单位
public static String beautifyUnit(long size) {
if (size <= 0) return "B";
final String[] units = new String[]{"B", "KB", "MB", "GB", "TB"};
int digitGroups = (int) (Math.log10(size) / Math.log10(1024));
return units[digitGroups];
}
//B转KB
public static String beautifyKb(long size) {
DecimalFormat df = new DecimalFormat("#.00");
String beauSize = "";
beauSize = df.format((double) size / 1024);
return beauSize;
}
//B转MB
public static String beautifyMb(long size) {
DecimalFormat df = new DecimalFormat("#.00");
String beauSize = "";
beauSize = df.format((double) size / 1048576);
return beauSize;
}
//B转GB
public static String beautifyGb(long size) {
DecimalFormat df = new DecimalFormat("#.00");
String beauSize = "";
beauSize = df.format((double) size / 1073741824);
return beauSize;
}
//B转TB
public static String beautifyTb(long size) {
DecimalFormat df = new DecimalFormat("#.00");
String beauSize = "";
beauSize = df.format((double) size / 1099511627776L);
return beauSize;
}
public static void main(String[] args) {
System.out.println(beautifySize(1));
System.out.println(beautifySize(2048));
System.out.println(beautifySize(200000));
System.out.println(beautifySize(200000000));
System.out.println(beautifySize(2000000000));
}
}
执行结果: