Java Number Format Pattern formatBytes(long bytes)

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

Description

Format bytes to KB, MB or GB.

License

Open Source License

Parameter

Parameter Description
bytes Bytes to format.

Return

Bytes formatted.

Declaration

public static String formatBytes(long bytes) 

Method Source Code

//package com.java2s;

import java.math.RoundingMode;
import java.text.DecimalFormat;

public class Main {
    /**/*from w  w w .  java  2s.c o  m*/
     * Format bytes to KB, MB or GB.
     * 
     * @param bytes
     *            Bytes to format.
     * @return Bytes formatted.
     */
    public static String formatBytes(long bytes) {
        double size = 0;
        if (bytes < 1024) {
            return bytes + " Bytes";
        } else if (bytes < 1048576) {
            size = bytes / 1024;
            return formatDecimal(size) + " KB";
        } else if (bytes < 1073741824) {
            size = bytes / 1048576;
            return formatDecimal(size) + " MB";
        } else {
            size = bytes / 1073741824;
            return formatDecimal(size) + " GB";
        }
    }

    /**
     * Format decimal numbers to #.##
     * 
     * @param size
     *            Size to format.
     * @return Decimal formatted.
     */
    public static String formatDecimal(double size) {
        DecimalFormat df = new DecimalFormat("#.###");
        df.setRoundingMode(RoundingMode.CEILING);
        return df.format(size);
    }
}

Related

  1. format(String value)
  2. formatAmtByComma(String amt, int len)
  3. formatBigNumber(long value)
  4. formatBitRate(long bytes)
  5. formatBytes(long bytes)
  6. formatBytes(long bytes)
  7. formatBytes(long bytes)
  8. formatBytes(long numBytes)
  9. formatDashboardNumber(Number amount)