Here you can find the source of formatBytesForDisplay(long amount)
Parameter | Description |
---|---|
amount | the amount of bytes |
public static String formatBytesForDisplay(long amount)
//package com.java2s; //License from project: Apache License import java.text.NumberFormat; import java.util.Locale; public class Main { /**/* w w w .j a va 2 s. co m*/ * Takes a byte size and formats it for display with 'friendly' units. * <p> * This involves converting it to the largest unit * (of B, KiB, MiB, GiB, TiB) for which the amount will be > 1. * <p> * Additionally, at least 2 significant digits are always displayed. * <p> * Negative numbers will be returned as '0 B'. * * @param amount the amount of bytes * @return A string containing the amount, properly formated. */ public static String formatBytesForDisplay(long amount) { double displayAmount = (double) amount; int unitPowerOf1024 = 0; if (amount <= 0) { return "0 B"; } while (displayAmount >= 1024 && unitPowerOf1024 < 4) { displayAmount = displayAmount / 1024; unitPowerOf1024++; } final String[] units = { " B", " KiB", " MiB", " GiB", " TiB" }; // ensure at least 2 significant digits (#.#) for small displayValues int fractionDigits = (displayAmount < 10) ? 1 : 0; return doubleToString(displayAmount, fractionDigits, fractionDigits) + units[unitPowerOf1024]; } /** * Converts a double to a string. * @param val The double to convert * @param precision How many characters to include after '.' * @return the double as a string. */ public static String doubleToString(double val, int maxFractionDigits) { return doubleToString(val, maxFractionDigits, 0); } private static String doubleToString(double val, int maxFractionDigits, int minFractionDigits) { NumberFormat f = NumberFormat.getNumberInstance(Locale.US); f.setMaximumFractionDigits(maxFractionDigits); f.setMinimumFractionDigits(minFractionDigits); return f.format(val); } }