2017-10-18 76 views
0

方法我有下面的代碼段:得到錯誤輸出,同時使用numberFormat.parse(「」)在Java

我傳遞值「55.00000000000000」並獲得輸出作爲55.00000000000001。

但是,當我通過「45.00000000000000」和「65.00000000000000」我得到輸出爲45.0和65.0。

有人可以幫助我得到正確的輸出爲55.0。

NumberFormat numberFormat = NumberFormat.getPercentInstance(Locale.US); 
if (numberFormat instanceof DecimalFormat) { 
    DecimalFormat df = (DecimalFormat) numberFormat; 
    df.setNegativePrefix("("); 
    df.setNegativeSuffix("%)"); 
} 
Number numericValue = numberFormat.parse("55.00000000000000%"); 
numericValue = new Double(numericValue.doubleValue() * 100); 
System.out.println(numericValue); 

回答

0

使用這行代碼

System.out.println(String.format("%.1f", numericValue)); 

哪裏格式方法使用格式化您的數據。

+0

謝謝但System.out.println(numericValue);我在覈心Java工作區中使用,但在實際代碼中沒有System.out.println語句。如何在println語句之前使用 –

1

這裏的問題是numericValue在數學上應該是0.55。但是,它將是Double(因爲numberFormat.parse()只能返回LongDouble)。並且Double不能完全保持0.55的值。請參閱this link瞭解原因的完整說明。結果是,當您用不精確的值進行進一步計算時,會發生舍入誤差,這就是爲什麼打印出來的結果不完全是確切的值。 (A Double也不能完全是0.45或0.65;只是當乘以100時,結果變爲正確的整數)。

當處理諸如貨幣或百分比的十進制值時,最好使用BigDecimal。如果NumberFormatDecimalFormat,你可以做一些事情,讓parse返回BigDecimal

if (numberFormat instanceof DecimalFormat) { 
    DecimalFormat df = (DecimalFormat) numberFormat; 
    df.setNegativePrefix("("); 
    df.setNegativeSuffix("%)"); 
    df.setParseBigDecimal(true); // ADD THIS LINE 
} 

現在,當您使用numberFormat.parse(),它返回Number將是一個BigDecimal,這是能夠保持精確值0.55。現在您必須避免將其轉換爲double,這會引入舍入誤差。相反,你應該說類似於

Number numericValue = numberFormat.parse("55.00000000000000%"); 
if (numericValue instanceof BigDecimal) { 
    BigDecimal bdNumber = (BigDecimal) numericValue; 
    // use BigDecimal operations to multiply by 100, then print or format 
    // or whatever you want to do 
} else { 
    // you're stuck doing things the old way, you might get some 
    // inaccuracy 
    numericValue = new Double(numericValue.doubleValue() * 100); 
    System.out.println(numericValue); 
}