文件大小转成可读的字符串


如题,使用本文中的 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;
}
相关标签

扫一扫

在手机上阅读