format Size in long to B KB MB GB - Android java.lang

Android examples for java.lang:long

Description

format Size in long to B KB MB GB

Demo Code

import android.text.TextUtils;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Main{

    public static String formatSize(long size, int decimalPoints) {
        return formatSize(size, decimalPoints, true);
    }/* w w  w.  ja v  a2s.c  o  m*/
    public static String formatSize(long size) {
        return formatSize(size, true);
    }
    public static String formatSize(long size, boolean includeUnits) {
        return formatSize(size, 2, includeUnits);
    }
    public static String formatSize(long size, int decimalPoints,
            boolean includeUnits) {

        int kb = 1024;
        int mb = kb * kb;
        int gb = mb * kb;

        if (size < 0)
            return "";

        int factor = (10 ^ decimalPoints);

        String ssize = "";

        if (size <= kb)
            ssize = size + " B";
        else if (size > kb && size <= mb)
            ssize = ((double) Math.round(((double) size / kb) * factor) / factor)
                    + (includeUnits ? " KB" : "");
        else if (size > mb && size <= gb)
            ssize = ((double) Math.round(((double) size / mb) * factor) / factor)
                    + (includeUnits ? " MB" : "");
        else if (size > gb)
            ssize = ((double) Math.round(((double) size / gb) * factor) / factor)
                    + (includeUnits ? " GB" : "");

        return ssize;
    }

}

Related Tutorials