Java Long Number Readable Format humanReadableByteCount(final long bytes, final boolean si)

Here you can find the source of humanReadableByteCount(final long bytes, final boolean si)

Description

formats the bytes to a human readable format

License

Apache License

Parameter

Parameter Description
si true if each kilo==1000, false if kilo==1024

Declaration

public static String humanReadableByteCount(final long bytes, final boolean si) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

public class Main {
    /**/*from   ww  w. j  av a2s  .  c o m*/
     * formats the bytes to a human readable format
     *
     * @param si
     *            true if each kilo==1000, false if kilo==1024
     */
    public static String humanReadableByteCount(final long bytes, final boolean si) {
        final int unit = si ? 1000 : 1024;
        if (bytes < unit)
            return bytes + " B";
        double result = bytes;
        final String unitsToUse = (si ? "k" : "K") + "MGTPE";
        int i = 0;
        final int unitsCount = unitsToUse.length();
        while (true) {
            result /= unit;
            if (result < unit)
                break;
            // check if we can go further:
            if (i == unitsCount - 1)
                break;
            ++i;
        }
        final StringBuilder sb = new StringBuilder(9);
        sb.append(String.format("%.1f ", result));
        sb.append(unitsToUse.charAt(i));
        if (si)
            sb.append('B');
        else
            sb.append('i').append('B');
        final String resultStr = sb.toString();
        return resultStr;
    }
}

Related

  1. humanNumber(long num)
  2. humanreadable(long bytes, boolean si)
  3. humanReadable(long memory)
  4. humanReadable(long number)
  5. humanReadableByteCount(final long bytes)
  6. humanReadableByteCount(long bytes)
  7. humanReadableByteCount(Long bytes, boolean decimal)
  8. humanReadableByteCount(long bytes, boolean si)
  9. humanReadableByteCount(long bytes, boolean si)