Java float type format to readable String as B KB MB GB

Description

Java float type format to readable String as B KB MB GB


import java.text.DecimalFormat;

public class Main {
    public static void main(String[] argv) throws Exception {
        float b = 2.45678f;
        System.out.println(byteToKMGB(b));
    }/*from   w w  w  .  j ava2 s .c o m*/

    public static String byteToKMGB(float b) {
        String kmgb = "";
        DecimalFormat df = new DecimalFormat("###.00");

        if (b < 1024) {
            kmgb = b + "B";
        } else if (b < 1024 * 1024) {
            kmgb = df.format(b / 1024) + "KB";
        } else if (b < 1024 * 1024 * 1024) {
            kmgb = df.format(b / 1024 / 1024) + "MB";
        } else {
            kmgb = df.format(b / 1024 / 1024 / 1024) + "GB";
        }
        return kmgb;
    }
}



PreviousNext

Related