tags:

views:

51

answers:

2

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}?

A: 

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
1 million is probably biggest value that my application can even handle, so I don't need anything complicated ...
newbie
That would require db change or java class changes, I rather just use jsp
newbie
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
+1  A: 
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