Java - Write code to format long value to readable form in B KB MB GB TB

Requirements

Write code to format long value to readable form in B KB MB GB TB

Demo

//package com.book2s;

public class Main {
    public static void main(String[] argv) {
        long value = 42;
        System.out.println(prettyBytes(value));
    }/*from   w w  w.  j  a  v a2s  . c o m*/

    public static String prettyBytes(long value) {

        String args[] = { "B", "KB", "MB", "GB", "TB" };
        StringBuilder sb = new StringBuilder();
        int i;
        if (value < 1024L) {
            sb.append(String.valueOf(value));
            i = 0;
        } else if (value < 1048576L) {
            sb.append(String.format("%.1f", value / 1024.0));
            i = 1;
        } else if (value < 1073741824L) {
            sb.append(String.format("%.2f", value / 1048576.0));
            i = 2;
        } else if (value < 1099511627776L) {
            sb.append(String.format("%.3f", value / 1073741824.0));
            i = 3;
        } else {
            sb.append(String.format("%.4f", value / 1099511627776.0));
            i = 4;
        }
        sb.append(' ');
        sb.append(args[i]);
        return sb.toString();
    }
}