2017-10-18 74 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); 
}