Java Size Format formatSize(long size)

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

Description

format Size

License

LGPL

Parameter

Parameter Description
size a parameter

Return

String

Declaration

public static String formatSize(long size) 

Method Source Code

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

import java.text.*;

public class Main {
    public static String formatSize(Object size) {
        if (size instanceof Integer) {
            return formatSize(((Integer) size).intValue());
        }/*from   ww w.j av  a2s. c  om*/
        if (size instanceof Long) {
            return formatSize(((Long) size).intValue());
        }
        return null;
    }

    /**
     * @param size
     * @return String
     */
    public static String formatSize(long size) {

        NumberFormat formatter = NumberFormat.getInstance();
        formatter.setMaximumFractionDigits(1);
        formatter.setMinimumFractionDigits(1);

        float mbValue = size;
        String format;
        if (mbValue < 1024) {
            format = formatter.format(mbValue) + " KB";
        } else {
            if (mbValue < 1048576) {
                mbValue /= 1024;
                format = formatter.format(mbValue) + " KB";
            } else {
                if (mbValue < 109970456576L) {
                    mbValue /= 1048576;
                    format = formatter.format(mbValue) + " MB";
                } else {
                    formatter.setMaximumFractionDigits(1);
                    formatter.setMinimumFractionDigits(1);
                    mbValue /= (float) 1048576;
                    format = formatter.format(mbValue) + " KB";
                }
            }
        }
        return format;
    }
}

Related

  1. formatSize(long longSize, int decimalPos)
  2. formatSize(long size)
  3. formatSize(long size)
  4. formatSize(long size)
  5. formatSize(long size)
  6. formatSize(long size, boolean forceFixLen, boolean forceSizeInBytes)
  7. formatSize(long sizeInByte)
  8. formatSize(long sizeInBytes)
  9. formatSizeInfo(long size)