Here you can find the source of format(double size, String type)
private static String format(double size, String type)
//package com.java2s; //License from project: Apache License public class Main { private static String format(double size, String type) { int precision = 0; if (size * 1000 % 10 > 0) { precision = 3;// www . ja va 2 s.c om } else if (size * 100 % 10 > 0) { precision = 2; } else if (size * 10 % 10 > 0) { precision = 1; } else { precision = 0; } String formatStr = "%." + precision + "f"; if ("KB".equals(type)) { return String.format(formatStr, (size)) + "KB"; } else if ("MB".equals(type)) { return String.format(formatStr, (size)) + "MB"; } else if ("GB".equals(type)) { return String.format(formatStr, (size)) + "GB"; } else if ("TB".equals(type)) { return String.format(formatStr, (size)) + "TB"; } else if ("PB".equals(type)) { return String.format(formatStr, (size)) + "PB"; } return String.format(formatStr, (size)) + "B"; } }