2016-06-28 193 views
2

我想要應用格式(後3位和後4位四捨五入),使用下面的代碼 -DecimalFormat的工作不正常

double a = 1231254125412512.231515235346; 
NumberFormat formatter = new DecimalFormat("#,###"); 
formatter.setRoundingMode(RoundingMode.HALF_UP); 
formatter.setMinimumFractionDigits(4); 
formatter.setMaximumFractionDigits(4); 
System.out.println("Number : " + formatter.format(a)); 

上面的代碼是對數-54125412512.231515235346(結果正常工作是-54,125,412,512.2315 )。

但它不適用於數字-1231254125412512.231515235346(結果-1,231,254,125,412,512.2000)。

+1

是變量'a' float還是double? – sidgate

+0

其雙雙a = 1231254125412512.231515235346; – malviyarahuljayendra

+0

由於Double具有53位的精度。所以它的最大值是17位數。 1231254125412512.231515235346〜1231254125412512.2(17位數字) – ThiepLV

回答

1

問題是您使用double變量,並且命中最大精度 Double.MIN_VALUE

SOURCE:

雙:其中52比特用於尾數(15到17個十進制數字,平均約16)64位(8個字節)。 11位用於指數,1位是符號位。

爲了避免這個問題使用BigDecimal代替:

BigDecimal a = new BigDecimal("-54125412512.231515235346"); 
BigDecimal b = new BigDecimal("-1231254125412512.231515235346"); 

NumberFormat formatter = new DecimalFormat("#,###"); 
formatter.setRoundingMode(RoundingMode.HALF_UP); 
formatter.setMinimumFractionDigits(4); 
formatter.setMaximumFractionDigits(4); 
System.out.println("Number : " + formatter.format(a)); 
System.out.println("Number : " + formatter.format(b)); 

OUTPUT:

Number : -54.125.412.512,2315 
Number : -1.231.254.125.412.512,2315 
+1

您的解決方案是正確的,但您的第一個陳述不是。 1231254125412512.231515235346 Double.MIN_VALUE。問題在於double沒有精確度來保存一個非常大的數字,並且精度非常高,所以它會被舍入。 –

+0

@ErwinBolwidt糾正並鏈接了一個源文件。非常感謝! –

+1

感謝您的幫助!理解了這個概念 – malviyarahuljayendra

2

雙人有53位,它是約16位的精度。