Java Math.pow() Rounding Error

早过忘川 提交于 2019-12-20 04:29:10

问题


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.



来源:https://stackoverflow.com/questions/11319415/java-math-pow-rounding-error

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!