wood burning stoves 2.0*
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 Murach's Java Servlets and JSP this week in the Servlets 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
Author

Restricting the number of floating point digits

Ransika deSilva
Ranch Hand

Joined: Feb 18, 2003
Posts: 524
Hello,
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
Sheriff

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();
number.setMaximumFractionDigits(2);
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

Preetham
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
 
Don't get me started about those stupid light bulbs.
 
subject: Restricting the number of floating point digits
 
Similar Threads
Lesson 1.7
Question from JQ+
Trim in java
Widening Conversion
How to count the number of digits after decimal point in java?