Java - Write code to convert long value to readable String in KB MB GB ...

Requirements

Write code to convert long value to readable String in KB MB GB ...

Demo

//package com.book2s;

public class Main {
    public static void main(String[] argv) {
        long bytes = 42;
        System.out.println(bytesToString(bytes));
    }//  ww  w .j  av a 2s .  com

    public static String bytesToString(long bytes) {

        int unit = 1024;
        if (bytes < unit)
            return bytes + " B";
        int exp = (int) (Math.log(bytes) / Math.log(unit));
        String pre = ("KMGTPE").charAt(exp - 1) + "";
        return String.format("%.1f %sB", bytes / Math.pow(unit, exp), pre);
    }
}