9

100,000,000 の数値がある場合、それを文字列で "100M" と表現するにはどうすればよいですか?

4

4 に答える 4

8

私の知る限り、数字の省略形をサポートするライブラリはありませんが、自分で簡単に行うことができます。

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 のような数値を短縮したくないことを前提としています。もしそうなら、この質問は重複しています。

于 2010-09-09T00:45:02.190 に答える
3

それを行うためのアルゴリズムがあります:

次のような地図が必要です

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

... 等々...

1)数値「num」を取得し、数値のlog10指数「ex」を計算してフロア化します。

注意

log10(0)が存在しないため、数値が0でないことを確認してください。また、20 = "2 ten"のように出力しても意味がないため、100より小さい場合は、数値をそのまま返す必要があります。

2)次に、上記のハッシュマップのキーを繰り返し処理し、キーが一致するかどうかを確認します。一致しない場合は、指数「ex」よりも小さいキーを取得します。

3)「ex」をこのキーに更新します!

4)今度は次のように数値をフォーマットします

num = num / pow(10、ex)

(!! exはハッシュマップのキーです!!)

5)これで、数値を特定の精度に丸めて出力できるようになりました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
于 2010-09-09T01:09:46.780 に答える
1

もう少し一般的なものにするための私の解決策は次のとおりです。

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];
}
于 2013-04-09T22:17:58.513 に答える