Skip to content

DoubleRounder Utility (Deprecated)

Marco Terzer edited this page Jun 14, 2017 · 2 revisions

DEPRECATED: Rounding Doubles with the DoubleRounder utility

DoubleRounder sometimes returns counter-intuitive results. The reason is that it performs mathematically correct rounding. For instance DoubleRounder.round(256.025d, 2) will be rounded down to 256.02 because the double value represented as 256.025d is somewhat smaller than the rational value 256.025 and hence will be rounded down.

Notes:

  • This behaviour is very similar to that of the BigDecimal(double) constructor (but not to valueOf(double) which uses the string constructor).
  • The problem can be circumvented with a double rounding step to a higher precision first, but it is complicated and we are not going into the details here.

For those reasons we cannot recommend to use DoubleRounder.

Example: Rounding Doubles with the DoubleRounder utility
public class RoundDouble {
	public static void main(String[] args) {
		final double oneSeventh = 1.0 / 7.0;
		final double twoThirds = 2.0 / 3.0;
		
		System.out.println(oneSeventh);
		System.out.println(twoThirds);

		double rounded17 = DoubleRounder.round(oneSeventh, 3);
		double rounded23 = DoubleRounder.round(twoThirds, 3);
		System.out.println(rounded17);
		System.out.println(rounded23);

		System.out.println(DoubleRounder.round(oneSeventh, 3, RoundingMode.DOWN));
		System.out.println(DoubleRounder.round(twoThirds, 3, RoundingMode.DOWN));

		System.out.println(DoubleRounder.round(oneSeventh, 10));
		System.out.println(DoubleRounder.round(twoThirds, 10));

		System.out.println(DoubleRounder.round(oneSeventh, 15));
		System.out.println(DoubleRounder.round(twoThirds, 15));

		final double oneTenthPow18 = Math.pow(0.1, 18);
		System.out.println();
		System.out.println(oneTenthPow18);
		System.out.println(DoubleRounder.round(oneTenthPow18, 18));
	}
}

will output:

0.14285714285714285
0.6666666666666666
0.143
0.667
0.142
0.666
0.1428571429
0.6666666667
0.142857142857143
0.666666666666667

1.000000000000001E-18
1.0E-18