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.
Floating point numbers do not have perfect precision. If that is an issue, use BigDecimal:
You don't need to split it,
Double.parseDouble
can handle those kinds of numbers just fine.See? It works!
0.0686357 is not exactly representable as a double-precision value.
Two solutions:
BigDecimal
.Double
will print always like that, but the value will remain correct. You'll need to format the output to get the correct value. SeeDecimalFormat
class.