Java Long Number Readable Format stringForBytes(long bytes)

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

Description

Return a human-readable indication of a size, given a number of bytes.

License

Apache License

Parameter

Parameter Description
bytes the number of bytes

Return

a string such as (1.23GB, 1.4MB, etc.)

Declaration

public static String stringForBytes(long bytes) 

Method Source Code

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

import java.text.*;

public class Main {
    /**//from w w  w .  j ava2 s  .  c o m
     * Return a human-readable indication of a size, given a number of bytes.
     * @param bytes the number of bytes
     * @return a string such as (1.23GB, 1.4MB, etc.)
     */
    public static String stringForBytes(long bytes) {
        DecimalFormat deci = new DecimalFormat("0.00");
        double gigs = (((double) bytes / 1024d) / 1024d / 1024d);
        double megs = (((double) bytes / 1024d) / 1024d);
        double kb = ((double) bytes / 1024d);
        if (gigs > 1) {
            return deci.format(gigs) + " GB";
        }
        if (megs > 1) {
            return deci.format(megs) + " MB";
        }
        if (kb > 1) {
            return deci.format(kb) + " KB";
        }
        return bytes + " bytes";
    }
}

Related

  1. humanReadableSize(long byteCount)
  2. humanReadableSize(long bytes)
  3. humanReadableTime(final long duration)
  4. humanTimeDiff(long timeDiff)
  5. readable(long bytes)
  6. stringify(long byteNumber)
  7. toHuman(long amount)
  8. toHumanReadableSize(long byteCount)
  9. toHumanReadableSize(long bytes)