Here you can find the source of bytesToString(int bytes)
public static String bytesToString(int bytes)
//package com.java2s; /*/*from www .j av a2 s . co m*/ * Copyright 2009 The Portico Project * * This file is part of pgauge (a sub-project of Portico). * * pgauge is free software; you can redistribute it and/or modify * it under the terms of the Common Developer and Distribution License (CDDL) * as published by Sun Microsystems. For more information see the LICENSE file. * * Use of this software is strictly AT YOUR OWN RISK!!! * If something bad happens you do not have permission to come crying to me. * (that goes for your lawyer as well) * */ public class Main { /** * Takes a given int representing a size in bytes and converts it to a String representing the * size. For example, 1024 would yield "1KB". Prints up to two decimal places. Uses "b" for * bytes, "KB" for kilobytes and "MB" for megabytes. */ public static String bytesToString(int bytes) { int kilobyte = 1024; int megabyte = kilobyte * kilobyte; String result = null; if (bytes >= megabyte) result = String.format("%.2f", reduce(bytes, megabyte)); else if (bytes >= kilobyte) result = String.format("%.2f", reduce(bytes, kilobyte)); else result = "" + bytes; // String.format() and all that rounds up (which I don't want) and in 1.5 we can't // specify the rounding mode on Decimal format, so I'm left to this hack. if (result.endsWith("00")) result = result.replace(".00", ""); else if (result.endsWith("0")) result = result.substring(0, result.length() - 1); if (bytes >= megabyte) return result + "MB"; else if (bytes >= kilobyte) return result + "KB"; else return result + "b"; } private static double reduce(int bytes, int unitSize) { int main = bytes / unitSize; double remainder = ((bytes % unitSize) / (double) unitSize); remainder = (double) ((int) (remainder * 100)) / 100; return ((double) main) + remainder; } }