Rounding to decimal places.

Mike Brooks
Greenhorn
Posts: 21
How would I round to whatever decimal place I choose, if its possible.

Ex.
double x = 3.56753656;

// Setting to 2 decimal places
DecimalFormat fmt = new DecimalFormat("0.##");

//I know about Math.round(x); and also fmt.format(x); but I want them
//both working together to round to the chosen deciaml place.
System.out.println("Answer is: " + ???help me here?? or??
[ March 11, 2006: Message edited by: Jon Martin ]

Tilo Hemp
Ranch Hand
Posts: 91
hi jon,

i can't contribute to the DecimalFormat question, but if you only need to do this conversion a few times, it might not be worth the creation of an additional object. in this case, i would prefer a hand-made code, e.g.

double fact = Math.pow(10, nDigits);
double rounded = Math.round(x*fact) / fact;

nDigits is the decimal place you want to round to. anyway, remember that the results might not be accurate, as the number of digits stored in the floating point numbers are finite. for example,

System.out.println(9999999.33f);

prints 9999999.0 as there is not enough place in the float to store the fraction exactly.

greetings
tilo

Mark Van Tuyl
Ranch Hand
Posts: 60
This will round and format a number simultaneously:According to Sun's API docs "DecimalFormat uses half-even rounding (see ROUND_HALF_EVEN) for formatting."

Jim Yingst
Wanderer
Sheriff
Posts: 18671
[Jon]:

//I know about Math.round(x); and also fmt.format(x); but I want them
//both working together to round to the chosen deciaml place.

Forget about round(), since it only rounds to the nearest integer value. Of course some simple math could be employed to use this to round to any arbitrary number of decimal places, but there are other classes that will do this more easily for you. DecimalFormat's format() can already do exactly what you want; if you "know about" it, I'm not sure what your question is.

Another option is available in JDK 5 via java.util.Formatter and various related classes:

[ March 12, 2006: Message edited by: Jim Yingst ]

Mike Brooks
Greenhorn
Posts: 21
Originally posted by Jim Yingst:
[QB]
Forget about round(), since it only rounds to the nearest integer value. Of course some simple math could be employed to use this to round to any arbitrary number of decimal places, but there are other classes that will do this more easily for you. DecimalFormat's format() can already do exactly what you want; if you "know about" it, I'm not sure what your question is. QB]

You're right. It already rounds. I feel stupid =0
[ March 12, 2006: Message edited by: Jon Martin ]