Calculate long value to readable Size - Java Language Basics

Java examples for Language Basics:long

Description

Calculate long value to readable Size

Demo Code


//package com.java2s;
import java.math.BigDecimal;

public class Main {
    public static void main(String[] argv) {
        long longSize = 12312342;
        System.out.println(toStringSize(longSize));
    }//w ww. jav  a 2  s .c o  m

    public static final long SIZE_BT = 1024L;
    public static final long SIZE_KB = SIZE_BT * 1024L;
    public static final long SIZE_MB = SIZE_KB * 1024L;
    public static final long SIZE_GB = SIZE_MB * 1024L;
    public static final int SACLE = 2;

    public static String toStringSize(Long longSize) {
        if (longSize >= SIZE_BT && longSize < SIZE_KB) {
            return longSize / SIZE_BT + "KB";
        } else if (longSize >= SIZE_KB && longSize < SIZE_MB) {
            return longSize / SIZE_KB + "MB";
        } else if (longSize >= SIZE_MB && longSize < SIZE_GB) {
            BigDecimal longs = new BigDecimal(Double.valueOf(longSize + "")
                    .toString());
            BigDecimal sizeMB = new BigDecimal(Double.valueOf(SIZE_MB + "")
                    .toString());
            String result = longs.divide(sizeMB, SACLE,
                    BigDecimal.ROUND_HALF_UP).toString();
            return result + "GB";
        } else if (longSize >= SIZE_GB) {
            BigDecimal longs = new BigDecimal(Double.valueOf(longSize + "")
                    .toString());
            BigDecimal sizeMB = new BigDecimal(Double.valueOf(SIZE_GB + "")
                    .toString());
            String result = longs.divide(sizeMB, SACLE,
                    BigDecimal.ROUND_HALF_UP).toString();
            return result + "TB";
        } else if (longSize < 0) {
            return "0B";
        } else {
            return longSize + "B";
        }
    }
}

Related Tutorials