2012-03-19 49 views

回答

44

來自here適應答案就應該是這個樣子

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

測試代碼:

for (long num : new long[] { 0, 27, 999, 1000, 110592, 
          28991029248L, 9223372036854775807L }) 
    System.out.printf("%20d: %8s%n", num, withSuffix(num)); 

輸出:

    0:  0 
        27:  27 
       999:  999 
       1000: 1.0 k 
       110592: 110.6 k 
     28991029248: 29.0 G 
9223372036854775807: 9.2 E 
+1

這真是太美了!謝謝。 – StackPWRequirmentsAreCrazy 2016-01-25 22:19:18

+0

如果decimal爲0,怎麼能使1.0k到1k? – 2016-06-30 11:14:28

+1

這個答案很美。 – Sotti 2016-09-10 23:40:53

相關問題