• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

float precision

 
p madhavi
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

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..

Thanks.
 
Steven Bell
Ranch Hand
Posts: 1071
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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:
34.69
34.68999904660607

[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 ]
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic