JAVA格式化文件大小字节数据("B", "KB", "MB", "GB", "TB")

 

 

/**
     * 格式化字节数据
     *
     * @param size 大小,单位字节
     */
    public static String formatSize(Long size) {
        if (size == null || size <= 0) {
            return "";
        }
        String[] units = {"B", "KB", "MB", "GB", "TB"};
        int unitIndex = (int) (Math.log10(size) / 3);
        double unitValue = 1 << (unitIndex * 10);
        return BigDecimal.valueOf(size / unitValue).setScale(2, RoundingMode.HALF_UP) + " " + units[unitIndex];
    }

 

使用

 public static void main(String[] args) {
        System.out.println(formatSize(3141366L));
    }

结果 (单位和数字之间会有一个空格)

3.00 MB

 

posted @ 2024-03-01 16:09  yvioo  阅读(13)  评论(0编辑  收藏  举报