This is Sun’s official advice:
BigDecimal class provides methods and properties for hendling numbers in very precise manner.
Let’s see how to use this class:
First of all, create BigDecimal object. For example:
BigDecimal result = new BigDecimal(0.00);
And let’s say we have two values to substract or multiply:
1234.123456789776 and 0.3888377362
In order to do this , java.math.BigDecimal has
BigDecimal add(BigDecimal augend) method for substracting numbers.
BigDecimal multiply(BigDecimal multiplicand) method for multiplying numbers
These, offcourse, are not the only method in this class. There are also other methods for mathematical operations. This was just taken for example…
result = (new BigDecimal(1234.123456789776)).add(new BigDecimal(0.3888377362));
To display the result, you can use the BigDecimal class's toString() method:
and the result would be:
Or you can display result using, for example BigDecimal class's doublevalue() method:
Which gives result:
Great thing about this class is ability to complitely control how some number needs to be rounded. In order to do this, we can use BigDecimal class's setScale() method.
In order to use it, you just need to specify how many decimal places you would like your number to have, and the logic of rounding it.
There are a lot ways to round it:
and many more…
For example, if we want to round our result to 2 decimal places, and to round it with ROUND_HALF_UP method, call:
result = result.setScale(2,BigDecimal.ROUND_HALF_UP);
and then, the result will be:
I never used this class before, untill today, when I noticed some wrong results while working on some software that needed very presice results…
BigDecimal class solved my problems…