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 Java in General and the fly likes float precision 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 » Java in General
Bookmark "float precision" Watch "float precision" New topic

float precision

p madhavi

Joined: Jun 10, 2005
Posts: 15

My java version is 1.3.1.
I have a float value ex: 34.68999904660606668687678978....
I want to have precision of 5 digits. I looked into Javaranch, found regarding BigDecimal and DecimalFormat, and Java API, but what is see mostly it works for doubles....but i want for float....
Any suggestions..

Steven Bell
Ranch Hand

Joined: Dec 29, 2004
Posts: 1071
There is no real difference between a float and a double other than a double is capable of storing larger values and is more accurate than a float can be.

The BigDecimal class exists because float and double types are inherently non-precise, because they are incapable of representing all numbers within their range. The BigDecimal class allows for precise floating point arithmetic.

If precision is not an issue I think Math.round will work for you.

Just so you know. The number you posted does not fit accuratly in either a float or a double so my guess is that you either need to use a double or BigDecimal. See the following code.

The output is:

[edit:] P.S. you will lose the precision as soon as the number is stored as a float or a double, so if you plan to use BigDecimal you should always deal with the number as a String or a BigDecimal.
[ June 15, 2005: Message edited by: Steven Bell ]
I agree. Here's the link:
subject: float precision
It's not a secret anymore!