2010-09-09 45 views
8

如果我有一个数字是100,000,000,那么我怎样才能将它表示为字符串中的“100M”?如何格式化长号码?

+0

切切实实的,这是一个重复的... – TheLQ 2010-09-09 00:34:29

+0

这是类似的,但并不完全是重复的:http://stackoverflow.com/questions/529432/java-format-number-in-millions – 2010-09-09 00:54:24

+0

这里有一个类它做了类似的事情:http://jcs.mobile-utopia.com/jcs/5242_ScaledNumberFormat.java,不幸的是它似乎不是支持库的一部分。 – oksayt 2010-09-09 00:59:30

回答

7

据我所知,有一个为缩写数字没有库的支持,但你可以轻松地做自己:

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); 
} 

当然,这是假定你不想缩短像1,234,567.89一个数字。如果你,那么这个问题是duplicate

+1

呵呵,如果num = 0呢?疑难杂症! – 2010-09-09 00:59:37

+0

什么,“0M”无效? ;) – 2010-09-09 01:04:48

2

有一个算法来做到这一点:

你需要一张地图,看起来像

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

...等等...

1)乘号“NUM “,计算该数字的log10指数”ex“并将其平面化。

注意

日志10(0)不存在,因此检查 的数目不为0,并因为它 没有意义来输出不同的是 像20 =“2 10”你应该返回 这个数字,因为如果它小于 比100!

2)现在迭代通过上面的哈希映射的键,看看是否匹配,如果没有采取小于指数“ex”的关键。

3)更新“ex”这个键!

4)现在现在格式化等

NUM = NUM​​/POW(10)!!

5的数目,前

(!! EX是散列映射的键))你可以将该数字四舍五入到一定的精确度和输出num + yourHash[ex]

一个例子:

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 
0

这里是我的解决方案,使其更通用:

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]; 
} 
0

这是更一般的解决方案。

public static String abbreviateNumber(long num) { 

    long temp = num/1000000; 
    if(temp > 0) { 
     return temp + "M+"; 
    } 

    temp = num/1000; 
    if (temp > 0) { 
     return temp + "K+"; 
    } 

    temp = num/500; 
    if (temp > 0) { 
     return "500+"; 
    } 

    temp = num/100; 
    if (temp > 0) { 
     return "100+"; 
    } 

    temp = num/50; 
    if (temp > 0) { 
     return "50+"; 
    } 

    temp = num/10; 
    if (temp > 0) { 
     return "10+"; 
    } 

    return String.valueOf(num); 
}