• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Double.parseDouble() Bug

 
vishal avad
Ranch Hand
Posts: 45
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi to all
i try following
int i = (int)(Double.parseDouble(("2.53")*100))
i value is 252
similarly for 2.51 it is 250
and for 2.55 it is 254
but for rest of the values it is working fine
thx in adv
vishal
 
Darryl Failla
Ranch Hand
Posts: 129
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I can't get this to compile at all; and it shouldn't compile. You are attempting to multiply a String and an integer. There is no multiply operator override for that.
 
Manfred Leonhardt
Ranch Hand
Posts: 1492
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Vishal,
This is not a bug just a fact of programming life. When dealing with IEEE floating point values you must realize that it is not integer arithmetic. Values usually calculated will vary about some epsilon value. Good starting point float: 1e-6, and double: 1e-12.
Your example also shows the problems with just truncating floating point values into integers and expecting some actual result.
In my opinion, when dealing with floating point numbers you should always use a round function or just make sure the value is between value + or - epsilon.
Regards,
Manfred.
 
vishal avad
Ranch Hand
Posts: 45
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thx darryl failla & Manfred Leonhardt
i read ur replys
darryl i m sorry i put one bracket in wrong place so it is not compiling
actual code is int i = (int)(Double.parseDouble("2.53")*100)
but still i m not satisfied with the answer
i just wanted to why it is happening with only 2.51 2.53 and 2.55
and not with the others
rgds
vishal
 
Jim Hall
Ranch Hand
Posts: 162
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I broke each line down separately and this is what I got:
<code>
double d = Double.parseDouble("2.53");
System.out.println(d);
d *= 100;
System.out.println(d);
int i = (int) d;
System.out.println(i);
Output
2.53
252.99999999999997
252
</code>
This doesn't occur if you use parseFloat().
[This message has been edited by Jim Hall (edited November 30, 2001).]
 
vishal avad
Ranch Hand
Posts: 45
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
thx Jim Hall
i can get the things which u get but my question is why it should happen.caz even blindly anyone can say 2.53*100 is 253 and not 252.99999999999997
can anybody explain this one in detail
thx in adv
vishal
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic