pretty print long value in B, KB, MB, GB, TB - Android java.lang

Android examples for java.lang:long

Description

pretty print long value in B, KB, MB, GB, TB

Demo Code

import java.io.ByteArrayOutputStream;
import java.io.PrintStream;

public class Main{

    /**/*from w w  w . j a v  a2  s .c  o  m*/
     * ?????????
     * @param value
     * @return
     */
    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();
    }

}

Related Tutorials