This week's book giveaway is in the Android forum.
We're giving away four copies of Head First Android and have Dawn & David Griffiths on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Double.parseDouble() Bug Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Head First Android this week in the Android forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Double.parseDouble() Bug" Watch "Double.parseDouble() Bug" New topic

Double.parseDouble() Bug

vishal avad
Ranch Hand

Joined: Nov 29, 2001
Posts: 45
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
Darryl Failla
Ranch Hand

Joined: Oct 16, 2001
Posts: 129
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.

Darryl Failla
Sun Certified Java 2 Programmer
Manfred Leonhardt
Ranch Hand

Joined: Jan 09, 2001
Posts: 1492
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.
vishal avad
Ranch Hand

Joined: Nov 29, 2001
Posts: 45
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
Jim Hall
Ranch Hand

Joined: Nov 29, 2001
Posts: 162
I broke each line down separately and this is what I got:
double d = Double.parseDouble("2.53");
d *= 100;
int i = (int) d;
This doesn't occur if you use parseFloat().
[This message has been edited by Jim Hall (edited November 30, 2001).]
vishal avad
Ranch Hand

Joined: Nov 29, 2001
Posts: 45
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
subject: Double.parseDouble() Bug
jQuery in Action, 3rd edition