How to format long numbers?

12,381

Solution 1

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.

Solution 2

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

Solution 3

Here's my solution to make it a little more generic:

private static final String[] magnitudes = new String[] {"", "K", "M"};

public static String shortenNumber(final Integer num) {
    if (num == null || num == 0) 
        return "0";

    float res = num;
    int i = 0;
    for (; i < magnitudes.length; i++) {
        final float sm = res / 1000;
        if (sm < 1) break;

        res = sm;
    }


    // don't use fractions if we don't have to
    return ( (res % (int) res < 0.1) ?
                String.format("%d", (int)res) :
                String.format("%.1f", res)
            ) 
            + magnitudes[i];
}
Share:
12,381
Sheehan Alam
Author by

Sheehan Alam

iOS, Android and Mac Developer. i can divide by zero.

Updated on June 04, 2022

Comments

  • Sheehan Alam
    Sheehan Alam almost 2 years

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