• Post Reply Bookmark Topic Watch Topic
  • New Topic

String representation af Double value 0.001  RSS feed

 
Janus Engstrøm
Ranch Hand
Posts: 44
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi ranchers,

A little puzzled by this:

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


With kind regards,
Janus
 
Campbell Ritchie
Marshal
Posts: 56599
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 .
 
Embla Tingeling
Ranch Hand
Posts: 237
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Janus Engstrøm wrote:new Double(0.001).toString() produces 0.0010


If you do,

new Double(0.0001).toString()

it becomes even worse doesn't it?

To get better control of your conversion you could use DecimalFormat.
 
Campbell Ritchie
Marshal
Posts: 56599
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Do people still use DecimalFormat now the % tags are available? How are you going to alter the number of # in the format string?
 
Janus Engstrøm
Ranch Hand
Posts: 44
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.


Best regards,
Janus
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!