Java Long Number Readable Format getHumanReadableSize(long bytes)

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

Description

Converts a long number representing bytes into human readable format.

License

Open Source License

Parameter

Parameter Description
bytes to format into a string.

Return

human readable format for larger byte counts.

Declaration

public static String getHumanReadableSize(long bytes) 

Method Source Code

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

import java.text.NumberFormat;

public class Main {
    /**// w  w w. ja v  a 2s.c  o m
     * Converts a long number representing bytes into human readable format.
     * <p>
     * This value is mainly for formating values like a file size, memory size
     * and so forth, so instead of seeing a large incoherent number you can see
     * something like '308.123KB' or '9.68MB'
     * @param bytes to format into a string.
     * @return human readable format for larger byte counts.
     */
    public static String getHumanReadableSize(long bytes) {

        long mb = (long) Math.pow(2, 20);
        long kb = (long) Math.pow(2, 10);
        long gb = (long) Math.pow(2, 30);
        long tb = (long) Math.pow(2, 40);

        NumberFormat nf = NumberFormat.getNumberInstance();
        nf.setMaximumFractionDigits(1);
        double relSize = 0.0d;
        long abytes = Math.abs(bytes);
        String id = "";
        if ((abytes / tb) >= 1) {
            relSize = (double) abytes / (double) kb;
            id = "TB";
        } else if ((abytes / gb) >= 1) {
            relSize = (double) abytes / (double) gb;
            id = "GB";
        } else if ((abytes / mb) >= 1) {
            relSize = (double) abytes / (double) mb;
            id = "MB";
        } else if ((abytes / kb) >= 1) {
            relSize = (double) abytes / (double) kb;
            id = "KB";
        } else {
            relSize = abytes;
            id = "b";
        }
        return nf.format((bytes < 0 ? -1 : 1) * relSize) + " " + id;
    }
}

Related

  1. formatBytes(long l)
  2. formatBytes(long size)
  3. getHumanReadable(long ts, boolean addUTC)
  4. getHumanReadableFileSize(Long fileSize)
  5. getHumanReadableIfSpeed(long ifSpeed)
  6. getHumanReadableSize(long fileSize)
  7. getHumanReadableSize(long size, long unit, String unitName)
  8. getHumanSize(long size)
  9. getMaxHeap(String message)