May 2003 Technical Tip – Java's BigDecimal class
We discussed the inherent imprecision of floating point arithmetic in the December 2002 article. We also proposed a solution in the January 2003 article. That solution involved doing all arithmetic with integers and using the modulus operator to isolate the whole and fractional parts of the number. This month we look at another solution: the BigDecimal class.
The BigDecimal class is part of the java.math package, so you'll need to import java.math.BigDecimal when you use it. BigDecimal objects are immutable, so most of the methods in this class return an instance of BigDecimal.
Here's the BigDecimal equivalent of the gas mileage example we saw in December:
Note the constructor in lines 6 and 7 accepts a String. Another constructor accepts a double: we could have replaced line 6 withBigDecimal begOdo = new BigDecimal(52390.7); but according to the API, "it is generally recommended that the (String) constructor be used in preference to this one." The subtract method in line 8 returns an instance of BigDecimal. The output appears as follows: You drove 166.4 miles.
Here's the BigDecimal equivalent of the sales tax example we saw in December:
Note the static methods valueOf in lines 6 and 7 which accept a long integer value and an integer scale. The value in line 6 is 123.45 and the value in line 7 is .065. The result of the multiplication in line 9 has a scale of five (two plus three) so we use the setScale method in line 10 to round the value to two decimal places. The output appears as follows:After tax amount is 131.47
Find out more by reading the BigDecimal class documentation in the Java API's at http://java.sun.com/j2se/1.4.1/docs/api/. Let me just mention here that the doubleValue method returns the value of a BigDecimal as a double, for example, double amtDue = afterTax.doubleValue();
Caliber Data Training is pleased to offer training in Java programming. We have recently rewritten our Visualage Java course to use WebSphere Studio Application Developer. We hope you will consider us when deciding upon a training provider!