文件大小轉成可讀的字符串

如題,使用本文中的 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;
}

所屬標簽

無標簽

25选5玩法中奖