Java Locale Format formatBytesForDisplay(long amount)

Here you can find the source of formatBytesForDisplay(long amount)

Description

Takes a byte size and formats it for display with 'friendly' units.

License

Apache License

Parameter

Parameter Description
amount the amount of bytes

Return

A string containing the amount, properly formated.

Declaration

public static String formatBytesForDisplay(long amount) 

Method Source Code


//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);
    }
}

Related

  1. formatarDataArquivoStr(String data)
  2. formatarNumeroBr(Double numero)
  3. formataValor(Double valor)
  4. formatBytes(final long bytes)
  5. formatBytes(long byteCount, Locale locale)
  6. formatComma(String number)
  7. formatDate(Calendar cal, String format)
  8. formatDate(Date date, String format)
  9. formatDate(Date date, String format)