package shop.alien.util.file;

import java.text.DecimalFormat;

/**
 * 文件大小计算工具类
 *
 * @author ssk
 * @version 1.0
 * @date 2020/5/7 15:03
 */
public class FileSizeCalcUtil {

    /**
     * 计算文件大小
     *
     * @return 返回合适的单位大小
     */
    public static String fileSizeCalculation(Double fileSize) {
        //大于10位转换为GB
        int gb = 10;
        //大于7位转换为MB
        int mb = 7;
        //取小数点后两位
        DecimalFormat df = new DecimalFormat("0.000");
        String lastSize;
        String sizeToString = df.format(fileSize);
        //判断文件大小
        String str = sizeToString.substring(0, sizeToString.indexOf("."));
        if (str.length() >= gb) {
            fileSize = fileSize / 1024 / 1024 / 1024;
            lastSize = df.format(fileSize) + "GB";
        } else if (str.length() >= mb) {
            fileSize = fileSize / 1024 / 1024;
            lastSize = df.format(fileSize) + "MB";
        } else {
            //转换为KB
            fileSize = fileSize / 1024;
            lastSize = df.format(fileSize) + "KB";
        }
        return lastSize;
    }
}
