在java中使用numberFormat.parse(";)方法时获得错误的输出
我有以下代码: 我正在传递值“55.00000000000000”,并获得55.00000000000001的输出 但当我通过“45.00000000000000”和“65.00000000000000”时,我得到的输出是45.0和65.0 有人能帮我得到正确的55.0输出吗在java中使用numberFormat.parse(";)方法时获得错误的输出,java,Java,我有以下代码: 我正在传递值“55.00000000000000”,并获得55.00000000000001的输出 但当我通过“45.00000000000000”和“65.00000000000000”时,我得到的输出是45.0和65.0 有人能帮我得到正确的55.0输出吗 NumberFormat numberFormat = NumberFormat.getPercentInstance(Locale.US); if (numberFormat instanceof DecimalForm
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);
使用这行代码
System.out.println(String.format("%.1f", numericValue));
格式化方法用于格式化数据。这里的问题是
numericValue
在数学上被假定为0.55。但是,它将是一个Double
(因为numberFormat.parse()
只能返回Long
或Double
)。而Double
不能精确地保持值0.55。有关原因的完整解释,请参阅。结果是,当您使用不精确的值进行进一步计算时,将出现舍入错误,这就是为什么打印出的结果不是精确值的原因。(ADouble
也不能精确地为0.45或0.65;恰好当乘以100时,结果舍入到正确的整数。)
在处理十进制值(如货币或百分比)时,最好使用BigDecimal
。如果NumberFormat
是DecimalFormat
,则可以设置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。现在,您必须避免将其转换为双精度,这将引入舍入错误。相反,你应该说
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);
}
谢谢,但是System.out.println(numericValue);我在核心java工作区中使用,但在实际代码中没有System.out.println语句。在println语句之前应该如何使用