Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/maven/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在java中使用numberFormat.parse(";)方法时获得错误的输出_Java - Fatal编程技术网

在java中使用numberFormat.parse(";)方法时获得错误的输出

在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

我有以下代码:

我正在传递值“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);
使用这行代码

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

格式化方法用于格式化数据。

这里的问题是
numericValue
在数学上被假定为0.55。但是,它将是一个
Double
(因为
numberFormat.parse()
只能返回
Long
Double
)。而
Double
不能精确地保持值0.55。有关原因的完整解释,请参阅。结果是,当您使用不精确的值进行进一步计算时,将出现舍入错误,这就是为什么打印出的结果不是精确值的原因。(A
Double
也不能精确地为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语句之前应该如何使用