1

大きな実数をカウントするために BigDecimal を使用しています。BigDecimal.toString()またはの2 つの方法を試し ましたBigDecimal.stripTrailingZeros().toString()が、それでも要件を満たしません。

たとえば、次のように使用するとstripTrailingZeros:4.3000になりますが、では4.3なく4.0なり4.0ます4。上記の方法は両方とも、これらの条件を満足させることはできません。だから、私の質問は次のとおりです。Javaでそれを行う方法は?

ありがとう :)

4

2 に答える 2

3

DecimalFormatクラスを調べます。あなたが望むのは次のようなものだと思います

DecimalFormat df = new DecimalFormat();
// By default, there will a locale specific thousands grouping. 
// Remove the statement if you want thousands grouping.
// That is, for a number 12345, it is printed as 12,345 on my machine 
// if I remove the following line.
df.setGroupingUsed(false);
// default is 3. Set whatever you think is good enough for you. 340 is max possible.
df.setMaximumFractionDigits(340);
df.setDecimalSeparatorAlwaysShown(false);
BigDecimal bd = new BigDecimal("1234.5678900000");
System.out.println(df.format(bd));
bd = new BigDecimal("1234.00");
System.out.println(df.format(bd));

Output:
1234.56789
1234

選択したRoundingModeを使用することもできます。DecimalFormatコンストラクターに提供されるパターンを使用して、表示する小数点の数を制御します。フォーマットの詳細については、DecimalFormatのドキュメントを参照してください。

于 2013-05-21T04:24:29.070 に答える