# round to two decimal places

• 11-26-2007, 05:49 PM
javaMike
round to two decimal places
is there an easy way to round a double to two decimal places?

i.e. 1.98999 would round to 1.99

the math.round method only rounds to nearest integer.

decimalformat class converts number to a string.

i figure there must be an easy way to do this...?? pls advise.
• 11-26-2007, 10:46 PM
hardwired
Code:

```double[] d = { 1.0/3.0, Math.PI, 2.0/3.0 }; for(int j = 0; j < d.length; j++) {     System.out.printf("d[%d] = %f%n", j, d[j]);     double d2 = (int)Math.round(d[j] * 100)/100.0;     System.out.printf("d2  = %f%n", d2); }```
• 12-23-2011, 03:46 PM
HansW
Re: round to two decimal places
Simple solution:

(Math.round(d*100))/100
• 12-24-2011, 03:01 AM
DarrylBurke
Re: round to two decimal places
Quote:

Originally Posted by HansW
Simple solution:

Wrong. Not a solution at all.

What Every Computer Scientist Should Know About Floating-Point Arithmetic

And since this thread is over 4 years old, I'm closing it. If you have any questions, please start your own thread.

db