File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Restricting the number of floating point digits 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 "Restricting the number of floating point digits" Watch "Restricting the number of floating point digits" New topic

Restricting the number of floating point digits

Ransika deSilva
Ranch Hand

Joined: Feb 18, 2003
Posts: 524
I just wanted to know how to restrict the number of floating point digits of a float value. I mean after the decimal point after have only 3 digits. like 20.111(only three 1s).
Thank you very much.

SCJP 1.4, SCMAD 1.0<br />SCWCD, SCBCD (in progress)
Dirk Schreckmann

Joined: Dec 10, 2001
Posts: 7023
Do you want to restrict this precision for display or calculation purposes?

[How To Ask Good Questions] [JavaRanch FAQ Wiki] [JavaRanch Radio]
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
You might consider not using floats. Use long or int to store the real number * 1000. Format the decimal places only for display. This is one way to make sure the 3-digit fractional part multplies, divides and rounds the way you'd expect. It might be fun to make your own number class that uses float for all input and output but hides ints internally.

A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
Preetham Chandrasekhar
Ranch Hand

Joined: Nov 05, 2003
Posts: 98
NumberFormat class has methods like setMaximumFractionDigits...

for example:

double d = 23.2323;
Numberformat number = NumberFormat.getNumberInstance();
String snum = number.format(d);
d = Double.parseDouble(snum);
// this would return 23.23

I know this is a bit complicated but it does what u need

SCJP 1.4

"In theory, there is no difference between theory and practice. But, in practice, there is."<br /> - Jan L.A. van de Snepscheut
I agree. Here's the link:
subject: Restricting the number of floating point digits
jQuery in Action, 3rd edition