I have a Double which I created like this:
Double d = Double.parseDouble( "27.86753" ); // All the digits of this double value are 27.867530822753906
This particular double can also be represented by a float, so Java drops the rest of my digits. How can I force Java to give me the true double representation (all of the digits) of this value?
Oh, man, interesting. You want to learn exactly how
doubledoes it inaccurately.I think
new BigDecimal(double).toString()will give you all of the incorrect digits, sinceBigDecimalrepresents a number with a precisely specified precision.EDIT: Ohhhhhhhh, I think I see what’s going on.
Let me try to explain it like this:
Double.toStringreturns the least preciseStringsuch thatDouble.parseDoublewill return exactly the samedouble— just enough digits to “uniquely identify” the exact IEEE 754 value, though the actual value may have more digits than are printed. Just becauseDouble.toStringisn’t giving you as many digits as you expect doesn’t mean that the actual IEEE 754 double-precision value is being rounded to that many digits.new BigDecimal(double).toStringwill return the exact IEEE-754 value being stored.UPDATE:
What’s going on is that when it prints out
27.86753, it’s actually internally a more precise value than the digits you’re quoting as the correct answer,27.867530822753906. That’s just becausetoStringis designed to print out only as much as necessary to ensure thatDouble.parseDouble(Double.toString(value))is a no-op.I ran the following code:
}
and it printed out
And indeed, this second value is noticeably closer to 27.86753, by a margin of something like 0.0000008.