Java Number Format Pattern formatBytes(long bytes)

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

Description

Format the bytes into readable text

License

Open Source License

Parameter

Parameter Description
bytes bytes

Return

bytes text

Declaration

public static String formatBytes(long bytes) 

Method Source Code

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

import java.text.DecimalFormat;

public class Main {
    /**/* w ww . j  a  v a2s.  c om*/
     * Format the bytes into readable text
     * 
     * @param bytes
     *            bytes
     * @return bytes text
     */
    public static String formatBytes(long bytes) {

        double value = bytes;
        String unit = "B";

        if (bytes >= 1024) {
            int exponent = (int) (Math.log(bytes) / Math.log(1024));
            exponent = Math.min(exponent, 4);
            switch (exponent) {
            case 1:
                unit = "KB";
                break;
            case 2:
                unit = "MB";
                break;
            case 3:
                unit = "GB";
                break;
            case 4:
                unit = "TB";
                break;
            }
            value = bytes / Math.pow(1024, exponent);
        }

        DecimalFormat df = new DecimalFormat("#.##");
        return df.format(value) + " " + unit;
    }
}

Related

  1. formatBigNumber(long value)
  2. formatBitRate(long bytes)
  3. formatBytes(long bytes)
  4. formatBytes(long bytes)
  5. formatBytes(long bytes)
  6. formatBytes(long numBytes)
  7. formatDashboardNumber(Number amount)
  8. formatDisplay(String displayString)
  9. formatDollar(Object obj)