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

1
  • We are not going to do your Home work, learn to use Google this problem has been solved thousands of times. Commented Oct 15, 2009 at 10:28

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

1 Comment

Exactly no loops please.
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"); } 

Comments

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.

3 Comments

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.