wood burning stoves 2.0*
The moose likes Beginning Java and the fly likes fixed length decimal numbers Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


JavaRanch » Java Forums » Java » Beginning Java
Bookmark "fixed length decimal numbers" Watch "fixed length decimal numbers" New topic
Author

fixed length decimal numbers

Namnai Kidorkar
Greenhorn

Joined: Jul 02, 2005
Posts: 25
How do I get fixed length decimal number in java float or double?

say, i've 22 and want to devide it with 7.

i want to get 3.14 not 3.14285.....

help please.
Ulf Dittmer
Marshal

Joined: Mar 22, 2005
Posts: 42023
    
  64
The java.text.NumberFormat class does this; check out in particular the setMaximumFractionDigits and setMinimumFractionDigits methods.
Of course, then you'll have a string, but you can convert it back easily enough.
[ September 29, 2005: Message edited by: Ulf Dittmer ]

Ping & DNS - my free Android networking tools app
Edwin Keeton
Ranch Hand

Joined: Jul 10, 2002
Posts: 214

1. Multiply the result times 100.
2. round()
3. Divide by 100


SCJP, SCWCD
Rick O'Shay
Ranch Hand

Joined: Sep 19, 2004
Posts: 531
>> I want to get 3.14 not 3.14285

In fact you really don't know what the value is until you observe it. So it makes sense to display it in the form you want while preserving the maximum precision the rest of the time.

double value = 3.143423432432;
System.out.printf("%.2f", value); // Prints: 3.14
Layne Lund
Ranch Hand

Joined: Dec 06, 2001
Posts: 3061
As Rick points out, you should make a distinction between how the number is stored and how it is displayed. When doing calculations, you should store the value as precisely as possible. However, when you display it, you can use either NumberFormat or, if you can use Java 5.0 features, PrintStream.printf() for the exact formatting you want.

Layne


Java API Documentation
The Java Tutorial
Naveen Vooka
Greenhorn

Joined: Oct 13, 2004
Posts: 25
Another alternate to round a double value, make a java.text.DecimalFormat like:
static DecimalFormat df=new DecimalFormat("0.00");
use
System.out.println(df.format(aDoubleValue));
and it does the rounding.

--------------
Naveen Vooka
www.devsquare.com
DevSquare - Online Application Development
 
Don't get me started about those stupid light bulbs.
 
subject: fixed length decimal numbers