2017-01-04 28 views
0

我想在下面的代碼基礎上,我年初設定的十進制格式四捨五入十進制數:如何在Java中舍入大十進制值?

DecimalFormat df = new DecimalFormat("#.000"); 
df.setRoundingMode(RoundingMode.FLOOR); 

double a = Double.parseDouble(df.format(43.473684210526315)); 
double b = Math.pow(a, 10); 
double c = Double.parseDouble(df.format(b)); 

System.out.println(a + " ** " + b + " ** " + c); 

,我得到的結果是:

43.473 ** 2.4109939006965688E16 ** 2.4109939006965688E16 

正如你請參閱a的值格式正確。而其他值不是。花了很長時間試圖瞭解正在發生的事情後,我發現2.4109939006965688E16的值無法格式化。在刪除E16後,我測試了相同的值,它工作。

我的問題是我怎麼能圓這麼大的小數,使其作爲a

+4

是你知道E16是什麼意思? – Florian

回答

1

這是幸​​運,a作品。如果初始值爲43.4701,您會看到43.47。在某些情況下,由於double的不準確性,您會看到3位小數。

在再次轉回double之前,您只使用DecimalFormatter創建String。你想保留並使用該字符串。

DecimalFormat df = new DecimalFormat("#.000"); 

double b = Math.pow(43.473684210526315, 10); 

String bFormatted = df.format(b); 

System.out.println(bFormatted); 

向你所需的輸出24115485538109308.000

1

爲了您的「大」小數您可以使用以下格式:

DecimalFormat df2 = new DecimalFormat("#.000E0"); 
1

我在這裏看到幾個問題:

  • 你不爲你的DecimalFormat指定區域。因此,DecimalFormat.formatDouble.parseDouble的組合很容易出錯,例如,與德語區域設置,DecimalFormat.format將使用逗號作爲小數點分隔符,Double.parseDouble不支持,並將拋出NumberFormatException。您應該同時使用DecimalFormat的formatparse
  • 此外,您直接使用您的雙倍數值爲System.out.println。爲什麼不連接DecimalFormat.format的結果,實現你想要的?例如。 System.out.println(df.format(a) + " ** " + df.format(b) + " ** " + df.format(c));
  • 如果您想要進行真正的數學舍入(例如需要雙倍數值進行其他計算),請使用Math.round。您可以乘以10,100,1000等,以達到所需的精度。請注意,使用double數據類型,您無法完成確切的舍入。
1

對於大的數字,你需要使用BigIntegerBigDecimal

DecimalFormat df = new DecimalFormat("#.000"); 
df.setRoundingMode(RoundingMode.FLOOR); 

BigDecimal a = new BigDecimal(43.473); 
BigDecimal b = a.pow(10); 

System.out.println(df.format(a) + " ** " + b.doubleValue() + " ** " + df.format(b)); 

這將導致下面的輸出

43.472 ** 2.4109939006965688E16 ** 24109939006965686.655