Rounding decimal digits

Price in Decimal digits is difficult to pay if your currency does not have low-value coins in circulation. So decimal digits might have to be rounded to the nearest value so that a figure like 0.56 can be paid. java.Math has MathContext and RoundingMode to round decimal digits.

So there is a precision that we specify. In the following code the precision is ‘1’ which means that .5625 is rounded to .6. We have rounded to 1 digit and the precision is lost but we ensure that the digits are either 0.5 or 0.6 depending on which is the nearest.

BigDecimal tax = new BigDecimal( 0.5625,
			new MathContext( 1,
 				RoundingMode.HALF_UP));

Output : 0.6

BigDecimal tax2 = new BigDecimal( 0.5325,
			new MathContext( 1,
				RoundingMode.HALF_UP));

Output : 0.5

BigDecimal tax2 = new BigDecimal( 0.5525,
			new MathContext( 1,
				RoundingMode.HALF_UP));

Output : 0.6 ( 0.55 is equidistant from 0.5 and 0.6. So it is rounded up to 0.6 )