3

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 not that long attribute, how can I do that, when I get Integer value to my jsp page for example ${myValue}?

Thomas Jung
  • 32,428
  • 9
  • 84
  • 114
newbie
  • 24,286
  • 80
  • 201
  • 301

3 Answers3

4

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):

Community
  • 1
  • 1
aioobe
  • 413,195
  • 112
  • 811
  • 826
3
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");
}
Thomas Jung
  • 32,428
  • 9
  • 84
  • 114
1

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.

duffymo
  • 305,152
  • 44
  • 369
  • 561
  • 1 million is probably biggest value that my application can even handle, so I don't need anything complicated ... – newbie Oct 15 '09 at 10:07
  • That would require db change or java class changes, I rather just use jsp – newbie Oct 15 '09 at 10:10
  • 1
    DB change? How so? No, it's just a change on the server side to turn it into a format that the JSP can use. You have to write a class to do the formatting anyway. There's no advantage to doing it on the JSP. – duffymo Oct 15 '09 at 23:44