Click to See Complete Forum and Search --> : Simple rounding question
How can I round a number to a certain number of decimal places?
i.e. if I wanted to round 3.141593456098 to three decimal places it would be 3.142. Is there an easy way to do this?
javasweeper
10-30-2006, 11:48 AM
Try BigDecimal if it suits your requirement. It has rounding and scaling options.
http://java.sun.com/j2se/1.4.2/docs/api/java/math/BigDecimal.html
agent_x91
11-01-2006, 05:55 AM
Math may also be appropriate if you wish to round it.
//round d to x decimal places
double rounded=(double)(Math.pow(10,x)/Math.round(Math.pow(10,x)*d));
Hope that helps.
I ended up using DecimalFormat although I really like agent x91's thinking :D
agent_x91
11-02-2006, 05:52 AM
:cool:
coop5885
11-19-2006, 01:07 PM
if nothing else you can format it in the output string using %.2f. just another solution