[Java][工具方法]格式化文件大小,自定义小数点后位数

2021-01-10 15点热度 0人点赞 0条评论

比较简单,直接干货

工具方法如下:
/**
* 
* @param bytes 文件大小,单位:字节数bytes
* @param precision 小数点后位数,可以是0
* @return 得到可读的文件的大小, 比如1.51 GB
*/
public static String readableFileSize(long bytes, int precision) {
        if (bytes <= 0) return "0";
        final String[] units = new String[]{"B", "KB", "MB", "GB", "TB", "PB"};
        int digitGroups = (int) (Math.log10(bytes) / Math.log10(1024));
        String pattern = precision <= 0 ? "0" : ("0." + new String(new char[precision]).replace("\0", "#"));
        return new DecimalFormat(pattern).format(bytes / Math.pow(1024, digitGroups)) + " " + units[digitGroups];
}

Python版本: https://blog.terrynow.com/2021/01/12/python-human-readable-file-size-with-precision/

Javascript版本:https://blog.terrynow.com/2021/01/09/javascript-human-readable-file-size/

Terry

文章评论

*

code