Reputation: 717
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.
Upvotes: 1
Views: 1609
Reputation: 1246
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.
Upvotes: 0
Reputation: 224952
You don't need to split it, Double.parseDouble
can handle those kinds of numbers just fine.
double number = Double.parseDouble("0.686357E-01");
Upvotes: 6
Reputation: 284836
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);
Upvotes: 1
Reputation: 272537
0.0686357 is not exactly representable as a double-precision value.
Two solutions:
BigDecimal
.Upvotes: 6