Here you can find the source of fileSizeString(long bytes)
public static String fileSizeString(long bytes)
//package com.java2s; /*/*w w w . j a v a 2s .co m*/ * $Id: StringUtils.java,v 1.3 2008-01-30 14:07:48 kashif Exp $ * * Copyright (C) 2002,2003 by Brockmann Consult (info@brockmann-consult.de) * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation. This program is distributed in the hope it will * be useful, but WITHOUT ANY WARRANTY; without even the implied warranty * of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. */ import java.text.DecimalFormat; import java.text.DecimalFormatSymbols; public class Main { private static final double ONE_KB = 1024.0; private static final double ONE_MB = 1024.0 * 1024.0; private static final double ONE_GB = 1024.0 * 1024.0 * 1024.0; private static DecimalFormat format; public static String fileSizeString(long bytes) { ensureFormat(); final StringBuffer result = new StringBuffer(64); double value; if (bytes >= ONE_GB) { value = scaleToThreeDecimals(bytes, ONE_GB); result.append(format.format(value)); result.append(" GB"); } else if (bytes >= ONE_MB) { value = scaleToThreeDecimals(bytes, ONE_MB); result.append(format.format(value)); result.append(" MB"); } else { value = scaleToThreeDecimals(bytes, ONE_KB); result.append(format.format(value)); result.append(" KB"); } return result.toString(); } private static void ensureFormat() { if (format == null) { format = new DecimalFormat("0.0"); format.setMaximumFractionDigits(3); format.setDecimalSeparatorAlwaysShown(true); final DecimalFormatSymbols symbols = new DecimalFormatSymbols(); symbols.setDecimalSeparator('.'); format.setDecimalFormatSymbols(symbols); } } private static double scaleToThreeDecimals(double value, double scale) { double upScaled = (1000.0 * value / scale); int truncated = (int) (upScaled + 0.5); return truncated * 0.001; } }