new Double(1).toString() produces 1.0
new Double(0.1).toString() produces 0.1
new Double(0.01).toString() produces 0.01
new Double(0.001).toString() produces 0.0010
-to which I totally agree ... except the last representation. Why has the String representation of 0.001 an extra trailing zero? I cannot find the answer to this in the API to Double.toString().
I'm using all the values listed above in a JComboBox, so I would prefer a "0.001" representation instead as it looks better. I know I can use Strings instead and then use the Double.parseDouble(String s) method to get the value, I'm only asking this question because I'm a little puzzled
I presume it has to do with the notorious imprecision of floating-point arithmetic. We have an FAQ (look for no 20) about that. If you need a specific number of figures, try the String.format method (you can alter the numbers after the % and before the f with the usual String-creation methods) or BigDecimal .
To get better control of your conversion you could use DecimalFormat.
posted 9 years ago
Do people still use DecimalFormat now the % tags are available? How are you going to alter the number of # in the format string?
posted 9 years ago
Thanks for the replies,
It's true that 0.0001d.toString() is even worse, but fortunately I don't need that kind of precision
The "problem" could very well be caused by the binary fractions and exponents used in the representation of the double value. But if that is so, why did it end up with a trailing zero, which doesn't (at least in my - somewhat ignorant - perception of mathematics) add any lesser or greater precision to 0.001? I could understand if the 0.001 value ended up being something like 0.001+delta where delta was a very small fraction. Oh well, let's not spend too much time on this, I'm aware of the imprecision of the double values, was just curious about the "exciting" String representation.
I AM MIGHTY! Especially when I hold this tiny ad:
how do I do my own kindle-like thing - without amazon