下面这种方法是歪果仁写的,来自于stackoverflow
public static String formatFileSize(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("#.00").format(size / Math.pow(1024, digitGroups)) + " " + units[digitGroups]; }
要转化的size为25 * 1024 * 1024 * 1024,运行100000次耗时300+
下面这种方法是国内搜索常见到的:
public static String formatFileSize(long size) {// 转换文件大小 DecimalFormat df = new DecimalFormat("#.00"); String fileSizeString = ""; if (size < 1024) { fileSizeString = df.format((double) size) + "B"; } else if (size < 1048576) { fileSizeString = df.format((double) size / 1024) + "K"; } else if (size < 1073741824) { fileSizeString = df.format((double) size / 1048576) + "M"; } else { fileSizeString = df.format((double) size / 1073741824) + "G"; } return fileSizeString; }
虽然代码行数比较多,如果要转化的size同样为25 * 1024 * 1024 * 1024,运行100000次耗时280+
各位自己挑着用