Java tutorial
//package com.java2s; import java.math.BigDecimal; public class Main { 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; } }