Java Locale Format formatBytes(final long bytes)

Here you can find the source of formatBytes(final long bytes)

Description

Pretty output of bytes, "1023 bytes", "1.1 kb", "523 kb", "1.7 Mb", "143 Gb" etc.

License

Open Source License

Parameter

Parameter Description
bytes a parameter

Declaration

public static String formatBytes(final long bytes) 

Method Source Code


//package com.java2s;
//License from project: Open Source License 

import java.math.BigDecimal;

import java.text.NumberFormat;

import java.util.Locale;

public class Main {
    public static final int KILO_BYTES = 1024;
    public static final BigDecimal KB_BD = new BigDecimal(KILO_BYTES);
    public static final int MEGA_BYTES = KILO_BYTES * 1024;
    public static final BigDecimal MB_BD = new BigDecimal(MEGA_BYTES);
    public static final int GIGA_BYTES = MEGA_BYTES * 1024;
    public static final BigDecimal GB_BD = new BigDecimal(GIGA_BYTES);

    /**/*from   ww  w . j a  v a2 s . co  m*/
     * Pretty output of bytes, "1023 bytes", "1.1 kb", "523 kb", "1.7 Mb", "143
     * Gb" etc.
     * 
     * @param bytes
     * @return
     */
    public static String formatBytes(final long bytes) {
        if (bytes < KILO_BYTES) {
            return String.valueOf(bytes) + " bytes";
        }
        if (bytes < MEGA_BYTES) {
            BigDecimal no = new BigDecimal(bytes).divide(KB_BD, 1, BigDecimal.ROUND_HALF_UP);
            if (no.longValue() >= 100) {
                no = no.setScale(0, BigDecimal.ROUND_HALF_UP);
            }
            return NumberFormat.getInstance(Locale.getDefault()).format(no) + " kb";
        }
        if (bytes < GIGA_BYTES) {
            BigDecimal no = new BigDecimal(bytes).divide(MB_BD, 1, BigDecimal.ROUND_HALF_UP);
            if (no.longValue() >= 100) {
                no = no.setScale(0, BigDecimal.ROUND_HALF_UP);
            }
            return NumberFormat.getInstance(Locale.getDefault()).format(no) + " Mb";
        }
        BigDecimal no = new BigDecimal(bytes).divide(GB_BD, 1, BigDecimal.ROUND_HALF_UP);
        if (no.longValue() >= 100) {
            no = no.setScale(0, BigDecimal.ROUND_HALF_UP);
        }
        return NumberFormat.getInstance(Locale.getDefault()).format(no) + " Gb";
    }
}

Related

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