## Wednesday, 2 March 2011

### Rounding Doubles

One of the problems with doubles is that you can never be sure of the number of decimals places that it will round to. This is an age old problem and in the bad old days, you had to do all the rounding yourself, which often lead to rounding errors. The usual way of attacking the problem was to write a rounding method based on the use of scaling:

```  private static void scalingMethod(double dbl) {         int ix = (int)(dbl * 100.0); // scale it     double dbl2 = ((double)ix)/100.0;     System.out.println("Scaling... dbl=" + dbl + ", dbl2=" + dbl2);   }```

Code like this has often been used, but is affected by a rounding error. For example, if the input is 12.3456 then this method will work; but, if the value of 12.3456 approaches 13.00 then the method fails.

#### Output to scalingMethod()

Scaling... dbl=12.3456, dbl2=12.34
Scaling... dbl=12.7896, dbl2=12.78

The solution to this age old problem is to use Java's inbuilt DecimalFormat class, which will do all the hard work for you.

```  private static void decimalFormatMethod(double dbl) {         DecimalFormat df = new DecimalFormat("#.##");     double dbl2 = Double.valueOf(df.format(dbl));     System.out.println("DecimalFormat... dbl=" + dbl + ", dbl2=" + dbl2);   }```

#### Output to decimalFormat()

DecimalFormat... dbl=12.3456, dbl2=12.35
DecimalFormat... dbl=12.7896, dbl2=12.79

As you can see, the input has been rounded correctly in both of the above input scenarios.