Java - Write code to format file Size to readable String

Requirements

Write code to format file Size to readable String

Demo

//package com.book2s;

import java.math.BigDecimal;

public class Main {
    public static void main(String[] argv) {
        long size = 41231232;
        System.out.println(fileSize2String(size));
    }/*from  ww w.  j  a  v a2s .com*/

    private static final float KB = 1024;
    private static final float MB = 1024 * 1024;
    private static final float GB = 1024 * 1024 * 1024;

    public static String fileSize2String(long size) {
        return fileSize2String(size, 2);
    }

    public static String fileSize2String(long size, int scale) {
        float result;
        String unit;
        if (size <= 0) {
            result = 0;
            unit = "B";
        } else if (size < KB) {
            result = size;
            unit = "B";
        } else if (size < MB) {
            result = size / KB;
            unit = "KB";
        } else if (size < GB) {
            result = size / MB;
            unit = "MB";
        } else {
            result = size / GB;
            unit = "GB";
        }
        BigDecimal bg = new BigDecimal(result);
        float f1 = bg.setScale(scale, BigDecimal.ROUND_HALF_UP)
                .floatValue();
        return f1 + unit;
    }
}

Related Exercise