Java Size Format formatSize(long bytes)

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

Description

Caller should append 'B' or 'b' as appropriate NOTE: formatDuration2() recommended in most cases for readability

License

Open Source License

Declaration

public static String formatSize(long bytes) 

Method Source Code

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

import java.text.DecimalFormat;

public class Main {
    /**//w  ww. ja v a2 s  . c o  m
     * Caller should append 'B' or 'b' as appropriate
     * NOTE: formatDuration2() recommended in most cases for readability
     */
    public static String formatSize(long bytes) {
        double val = bytes;
        int scale = 0;
        while (val >= 1024) {
            scale++;
            val /= 1024;
        }

        DecimalFormat fmt = new DecimalFormat("##0.00");

        String str = fmt.format(val);
        switch (scale) {
        case 1:
            return str + "K";
        case 2:
            return str + "M";
        case 3:
            return str + "G";
        case 4:
            return str + "T";
        case 5:
            return str + "P";
        case 6:
            return str + "E";
        case 7:
            return str + "Z";
        case 8:
            return str + "Y";
        default:
            return bytes + "";
        }
    }
}

Related

  1. formatMemorySize(long size)
  2. formatPartSize(int size, NumberFormat format)
  3. formatSize(double fileSize)
  4. formatSize(double size)
  5. formatSize(int size)
  6. formatSize(long bytes)
  7. formatSize(long bytes)
  8. formatSize(long fileSize)
  9. formatSize(long longSize)