This week's book giveaway is in the Jobs Discussion forum.
We're giving away four copies of Java Interview Guide and have Anthony DePalma on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Float.parseFloat(string) not accurate conversion Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of Java Interview Guide this week in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Float.parseFloat(string) not accurate conversion" Watch "Float.parseFloat(string) not accurate conversion" New topic

Float.parseFloat(string) not accurate conversion

R Joshi

Joined: Feb 21, 2006
Posts: 13
I understand that dealing with floats is not an accurate science .
But can I somehow specify that I need a correct precision upto 'n' digit after decimal point. How does 'rounding' work for floats? See the second example.

String s=5555.1234, Float.parseFloat(s)=5555.1235, Float.valueOf(s)=5555.1235 <===Note 5 at the end ?

String s=5555.6789, Float.parseFloat(s)=5555.6787, Float.valueOf(s)=5555.6787 <=== Note 7 at the end?

String s=5555.67898898098989797987987987987, Float.parseFloat(s)=5555.679, Float.valueOf(s)=5555.679 <== why only 3 digit at the end ?

I am using JDK1.5


B&S(2.3.1)<br />There are no stupid questions. Answers maybe
Yuriy Zilbergleyt
Ranch Hand

Joined: Dec 13, 2004
Posts: 429
Is there a reason you are using floats instead of doubles? Switching to doubles would fix this issue.

But it really is a weird one. I just tried parsing those strings to a double and the casting to a float, and the result was messed up again.

I agree. Here's the link:
subject: Float.parseFloat(string) not accurate conversion
It's not a secret anymore!