2010-09-09 30 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); 
}