[float]s and [double]s are useful for graphics and possible statistics.However they are not recommended for certain calculations requiring absoluteaccuracy, such as when they involve money . That’s because the results produced by [float]ing point and [double] precision math is sometimes inaccurate due to data representation in the computer. Think in terms of:
double f = 2.9 - 1.1;System.out.println( f );giving: 1.7999999999999998 instead of 1.8Enter the [BigDecimal] number.....import java.math.*;class BigDecimalTest { public static void main(String[] args) { BigDecimal a = new BigDecimal("2.9"); BigDecimal b = new BigDecimal("1.1"); BigDecimal c = a.subtract(b); // Note the convention. System.out.println(c); // An accurate value: 1.800000000 =) }}
Notice that it prints all the digits? To format it…
BigDecimal trim(BigDecimal n) // trim ( (BigDecimal) a) to cut off alltrailing zeros{ try { while (true) { n = n.setScale(n.scale()-1); } } catch (ArithmeticException e) {
// Not “real” error: No more trailing zeroes -> Just exit // setScale() tries to eliminate a non-zero digit -> Out of the loop // Remember exceptions are not recommended for exiting loops, but this seems to be the best way…
} return n;}BigDecimal format(BigDecimal n, int dp) // Sets [n] to [dp] decimal places{ return n.setScale(dp, BigDecimal.ROUND_HALF_UP); // Sets scale and roundsup if most significant (cut off) number >= 5}
Examples:
trim(new BigDecimal("2.320000")) -> 2.32format(new BigDecimal("1.4553"), 2) -> 1.46format(new BigDecimal("87"), 7) -> 87.0000000