2013-05-21 93 views
1

我使用BigDecimal來計算一些大的實數。雖然我嘗試了兩種方法: BigDecimal.toString()BigDecimal.stripTrailingZeros().toString(),但它仍不能滿足我的要求。Java BigDecimal:如何fortmat BigDecimal

例如,如果我用stripTrailingZeros4.3000成爲4.34.0成爲4.04。上述兩種方法都不能撼動這些條件。所以,我的問題是:如何在java中完成它?

謝謝:)

回答

3

您可以使用DecimalFormat如下:

BigDecimal a = new BigDecimal("4.3000"); 
BigDecimal b = new BigDecimal("4.0"); 

DecimalFormat f = new DecimalFormat("#.#"); 
f.setDecimalSeparatorAlwaysShown(false) 
f.setMaximumFractionDigits(340); 

System.out.println(f.format(a)); 
System.out.println(f.format(b)); 

它打印

4.3 
4 

由於Bhashit指出,小數位默認數量爲3,但是我們可以將其設置爲340的最大值。實際上我並不知道DecimalFormat的這種行爲。這意味着如果您需要超過340個小數位,您可能需要自己操作由toString()給出的string

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文檔。

+0

我不確定這是他/她正在尋找的行爲。我認爲他們正在尋找剝離所有尾隨零。 – Zong

+0

更新了答案。感謝您的評論。我錯讀了這個問題。 –