Java Math.pow() Rounding Error

2019-02-28 20:28发布

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.

标签: java double
4条回答
唯我独甜
2楼-- · 2019-02-28 20:57

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);
查看更多
男人必须洒脱
3楼-- · 2019-02-28 21:13

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!

查看更多
Viruses.
4楼-- · 2019-02-28 21:19

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.
查看更多
放我归山
5楼-- · 2019-02-28 21:20

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.

查看更多
登录 后发表回答