Converting values to unit prefixes in JSP page

后端 未结 3 1074
迷失自我
迷失自我 2021-01-14 06:39

How can I convert values to to other units in JSP page. For example if I get value 1001 and I want to only display 1K, or when I get 1 000 001 I would like to display 1M and

3条回答
  •  醉酒成梦
    2021-01-14 07:16

    This problem can (and should in my opinion) be solved without loops.

    Here's how:

    public static String withSuffix(long count) {
        if (count < 1000) return "" + count;
        int exp = (int) (Math.log(count) / Math.log(1000));
        return String.format("%.1f %c",
                             count / Math.pow(1000, exp),
                             "kMGTPE".charAt(exp-1));
    }
    

    Test code:

    for (long num : new long[] { 0, 27, 999, 1000, 110592,
                                 28991029248L, 9223372036854775807L })
       System.out.printf("%20d: %8s%n", num, withSuffix(num));
    

    Output:

                       0:        0
                      27:       27
                     999:      999
                    1000:    1.0 k
                  110592:  110.6 k
             28991029248:   29.0 G
     9223372036854775807:    9.2 E
    

    Related question (and original source):

    • How to convert byte size into human readable format in java?

提交回复
热议问题