PHP
·
发表于 5年以前
·
阅读量:8312
如题,使用本文中的 convertSize2String
方法,即可以将 long
的值,转为KB
,MB
,GB
,并通过参数precision
指定小数点的位数。调用方用法如下:
// 第二个参数,2 表示保留小数点后二位。
convertSize2String(123121,2);
public static String convertSize2String(long size, int precision) {
if (size <= 0) {
return "0B";
}
int divide = 1024;
double curDivide = (long) StrictMath.pow(divide, 3);
double result = size / curDivide;
if (result >= 1) {
return getStringOfDouble(result, precision) + "GB";
}
curDivide = (long) StrictMath.pow(divide, 2);
result = size / curDivide;
if (result >= 1) {
return getStringOfDouble(result, precision) + "MB";
}
curDivide = (long) StrictMath.pow(divide, 1);
result = size / curDivide;
if (result >= 1) {
return getStringOfDouble(result, precision) + "KB";
}
return getStringOfDouble(size, precision) + 'B';
}
private static String getStringOfDouble(double d, int precision) {
String str = String.valueOf(d);
int index = str.indexOf('.');
if (index > 0 && index + precision <= str.length()) {
if (index + precision < str.length()) {
str = str.substring(0, index + precision + 1);
} else {
str = str.substring(0, index + precision);
}
while (str.endsWith("0")) {
str = str.substring(0, str.length() - 1);
}
if (str.endsWith(".")) {
str = str.substring(0, str.length() - 1);
}
}
return str;
}