Java long type format to readable String as B KB MB GB

Description

Java long type format to readable String as B KB MB GB


import java.text.DecimalFormat;

public class Main {
    public static void main(String[] argv) throws Exception {
        long fileSize = 123123123;
        System.out.println(formatFileSize(fileSize));
    }//from   w  w  w.ja v  a  2s  .c o m

    public static String formatFileSize(long fileSize) {
        DecimalFormat df = new DecimalFormat("#.00");
        String fileSizeString = "";
        if (fileSize < 0) {
            fileSizeString = String.valueOf(fileSize);
        } else if (fileSize < 1024) {
            fileSizeString = df.format((double) fileSize) + "B";
        } else if (fileSize < 1048576) {
            fileSizeString = df.format((double) fileSize / 1024) + "K";
        } else if (fileSize < 1073741824) {
            fileSizeString = df.format((double) fileSize / 1048576) + "M";
        } else {
            fileSizeString = df.format((double) fileSize / 1073741824) + "G";
        }
        return fileSizeString;
    }
}

Java long type format to String via bit operator


public class Main {
    public static void main(String[] argv) throws Exception {
        long size = 897987234L;
        System.out.println(getSizeDesc(size));
    }/*from  ww w  .ja  v a  2s. co  m*/

    public static String getSizeDesc(long size) {
        String suffix = "B";
        if (size >= 1024) {
            suffix = "K";
            size = size >> 10;
            if (size >= 1024) {
                suffix = "M";
                // size /= 1024;
                size = size >> 10;
                if (size >= 1024) {
                    suffix = "G";
                    size = size >> 10;
                    // size /= 1024;
                }
            }
        }
        return size + suffix;
    }
}



PreviousNext

Related