Here you can find the source of formatSize(long size, boolean forceFixLen, boolean forceSizeInBytes)
public static String formatSize(long size, boolean forceFixLen, boolean forceSizeInBytes)
//package com.java2s; //License from project: Open Source License import java.text.*; public class Main { private static DecimalFormat decFmtFix1 = null; private static DecimalFormat decFmtMax1 = null; private static NumberFormat intFmt = null; public static String formatSize(long size, boolean forceFixLen, boolean forceSizeInBytes) { StringBuilder buf = new StringBuilder(64); appendSizeText(buf, size, forceFixLen, forceSizeInBytes); return buf.toString(); }/*from w ww .j a v a 2 s . c o m*/ public static void appendSizeText(StringBuilder buf, long size, boolean forceFixLen, boolean forceSizeInBytes) { DecimalFormat decFmt = forceFixLen ? getDecimalFormatFix1() : getDecimalFormatMax1(); final long kb = 1024L; final long mb = kb * 1024L; final long gb = mb * 1024L; if (size >= gb) { buf.append(decFmt.format((double) size / (double) gb)); buf.append(" GByte"); } else if (size >= mb) { buf.append(decFmt.format((double) size / (double) mb)); buf.append(" MByte"); } else if (size >= kb) { buf.append(decFmt.format((double) size / (double) kb)); buf.append(" KByte"); } if (buf.length() > 0) { if (forceSizeInBytes) { buf.append(" ("); buf.append(getIntegerFormat().format(size)); buf.append(" Bytes"); buf.append((char) ')'); } } else { buf.append(getIntegerFormat().format(size)); buf.append(" Bytes"); } } public static DecimalFormat getDecimalFormatFix1() { if (decFmtFix1 == null) { NumberFormat numFmt = NumberFormat.getNumberInstance(); if (numFmt instanceof DecimalFormat) { decFmtFix1 = (DecimalFormat) numFmt; } else { decFmtFix1 = new DecimalFormat(); } decFmtFix1.applyPattern("###,##0.0"); } return decFmtFix1; } public static DecimalFormat getDecimalFormatMax1() { if (decFmtMax1 == null) { NumberFormat numFmt = NumberFormat.getNumberInstance(); if (numFmt instanceof DecimalFormat) { decFmtMax1 = (DecimalFormat) numFmt; } else { decFmtMax1 = new DecimalFormat(); } decFmtMax1.setMaximumFractionDigits(1); } return decFmtMax1; } public static NumberFormat getIntegerFormat() { if (intFmt == null) { intFmt = NumberFormat.getIntegerInstance(); intFmt.setGroupingUsed(true); } return intFmt; } }