Java Math.pow() Rounding Error

2019-02-28 20:38发布

问题:

I'm having trouble with (what I suspect is) a rounding error.

I have a string, 0.686357E-01, which I'm trying to convert to a double. I've been able to split it up using the Pattern.split() function, and I'm capturing the base and the exponent values just fine. However, once I try to multiply them appropriately, I get this as a result: 0.06863570000000001.

Here's my relevant code:

pattern = Pattern.compile("E\\+?");
String[] number = pattern.split(string);

double base = Double.parseDouble(number[0]);
int exponent = Integer.parseInt(number[1]);

number= base*Math.pow(10, exponent);

So, how do I avoid the rounding error? (There are ways that I can work around it, but if it's possible to do, then I'd like to know how to fix the issue)

Thanks.

回答1:

You don't need to split it, Double.parseDouble can handle those kinds of numbers just fine.

double number = Double.parseDouble("0.686357E-01");

See? It works!



回答2:

0.0686357 is not exactly representable as a double-precision value.

Two solutions:

  • Use e.g. BigDecimal.
  • Limit the displayed precision to a certain number of significant figures when converting back to human-readable.


回答3:

Floating point numbers do not have perfect precision. If that is an issue, use BigDecimal:

String string = "0.686357E-01";
BigDecimal number = new BigDecimal(string);
System.out.println(number);


回答4:

Double will print always like that, but the value will remain correct. You'll need to format the output to get the correct value. See DecimalFormat class.



标签: java double