Converting values to unit prefixes in JSP page

后端 未结 3 1050
迷失自我
迷失自我 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:15
    static String toSymbol(int in) {
        String[] p = { "", "K", "M", "G" };
        int k = 1000;
        assert pow(k, p.length) - 1 > Integer.MAX_VALUE;
        int x = in;
        for (int i = 0; i < p.length; i++) {
            if (x < 0 ? -k < x : x < k) return x + p[i];
            x = x / k;
        }
        throw new RuntimeException("should not get here");
    }
    
    0 讨论(0)
  • 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?
    0 讨论(0)
  • 2021-01-14 07:19

    Maybe you could write a custom implementation of java.text.Format or override java.text.NumberFormat to do it. I'm not aware of an API class that does such a thing for you.

    Or you could leave that logic in the class that serves up the data and send it down with the appropriate format. That might be better, because the JSP should only care about formatting issues. The decision to display as "1000" or "1K" could be a server-side rule.

    0 讨论(0)
提交回复
热议问题