Java tutorial
//package com.java2s; import java.math.BigDecimal; public class Main { public static String getFormatSize(double size) { if (0 == size) { return "0K"; } double kiloByte = size / 1024; double megaByte = kiloByte / 1024; if (megaByte < 1) { BigDecimal result1 = new BigDecimal(Double.toString(kiloByte)); return result1.setScale(2, BigDecimal.ROUND_HALF_UP).stripTrailingZeros().toPlainString() + "K"; } double gigaByte = megaByte / 1024; if (gigaByte < 1) { BigDecimal result2 = new BigDecimal(Double.toString(megaByte)); return result2.setScale(2, BigDecimal.ROUND_HALF_UP).stripTrailingZeros().toPlainString() + "M"; } double teraBytes = gigaByte / 1024; if (teraBytes < 1) { BigDecimal result3 = new BigDecimal(Double.toString(gigaByte)); return result3.setScale(2, BigDecimal.ROUND_HALF_UP).stripTrailingZeros().toPlainString() + "G"; } BigDecimal result4 = new BigDecimal(teraBytes); return result4.setScale(2, BigDecimal.ROUND_HALF_UP).stripTrailingZeros().toPlainString() + "T"; } }