views:

94

answers:

2

If I have a number that is 100,000,000 how can I represent that as "100M" in a string?

+3  A: 

To my knowledge there's no library support for abbreviating numbers, but you can easily do it yourself:

NumberFormat formatter = NumberFormat.getInstance();
String result = null;
if (num % 1000000 == 0 && num != 0) {
   result = formatter.format(num / 1000000) + "M";
} else if (num % 1000 == 0 && num != 0) {
   result = formatter.format(num / 1000) + "K";
} else {
   result = formatter.format(num);
}

Of course, this assumes that you don't want to shorten a number like 1,234,567.89. If you do, then this question is a duplicate.

Aaron Novstrup
hehe, what if num=0? Gotcha!
GregS
What, "0M" isn't valid? ;)
Aaron Novstrup
A: 

There is an algorithm to do that:

You need a map that looks like

2 => "hundred"
3 => "thousand"
6 => "million"
9 => "billion"
12 => "trillion"
15 => "quadrillion"

... and so on...

1) Take the number "num", calculate the log10 exponent "ex" of the number and floor it.

Attention

log10(0) doesn't exist so check that the number is not 0 and since it doesn't make sense to output something like 20 = "2 ten" you should return the number as it is if it's smaller than 100 !

2) Now iterate thru the keys of the hash map above and look if a key matches, if not take the key that is smaller than the exponent "ex".

3) Update "ex" to this key!

4) Now format the number like

num = num / pow(10, ex)

(!! ex is a key of the hash map !!)

5) now you could round the number to a certain precision and output num + yourHash[ex]

An example:

number = 12345.45
exponent = floor(log10(12345.45))

exponent should now be 4 !

look for a key in the hash map -- whoops no key matches 4 ! -- so take 3 !

set exponent to 3 

now you scale the number:

number = number / pow(10, exponent)

number = 12345.45 / pow(10, 3) 

number = 12345.45 / 1000

number is now 12.34545

now you get the value to the corresponding key out of the hash map

the value to the key, which is 3 in this example, is thousand  

so you output 12.34545 thousand
sled