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 ]

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.

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.

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

<a href="http://www.catb.org/~esr/faqs/smart-questions.html" target="_blank" rel="nofollow">How To Ask Smart Questions</a>

//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 ]

"I'm not back." - Bill Harding, Twister

Mike Brooks
Greenhorn

Joined: Mar 08, 2006
Posts: 21

posted

0

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 ]