wood burning stoves 2.0*
The moose likes Java in General and the fly likes Rounding BigDecimal Calculation Yielded Wrong Result Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Rounding BigDecimal Calculation Yielded Wrong Result" Watch "Rounding BigDecimal Calculation Yielded Wrong Result" New topic

Rounding BigDecimal Calculation Yielded Wrong Result

James Gordon
Ranch Hand

Joined: Aug 09, 2002
Posts: 106
Hello All,

The first println yielded 4.15
The second println yielded 4.980

Doing it manually, the result should be indeed 4.98

Does this imply that we should not use BigDecimal for calculations?

Thanks in advance.
[ September 22, 2004: Message edited by: James Gordon ]
Joyce Lee
Ranch Hand

Joined: Jul 11, 2003
Posts: 1392
Hi James,

I think it's still possible to use BigDecimal for the calculation if the scale value is set higher. Then round off the final value to 2 or 3 decimal places.

[ September 22, 2004: Message edited by: Joyce Lee ]
David Hibbs
Ranch Hand

Joined: Dec 19, 2002
Posts: 374
Keep in mind that you have yourself specified the number of significant digits to carry. BigDecimal has another divide method that does not require a scale:

public BigDecimal divide(BigDecimal val,
int roundingMode)Returns a BigDecimal whose value is (this / val), and whose scale is this.scale(). If rounding must be performed to generate a result with the given scale, the specified rounding mode is applied.

I have yet to see this method fail in standard calculations with a known-to-be-precise answer.


*You can always cover yourself with a NumberFormat that only allows 2 decimal places.
*BigDecimal also provides many rounding modes to choose from,
*You can always modify operator order to clarify what the result should be
*Your operands define the inital scale of the result

Play around with the following code some. Note that I don't specify a scale.

If you pass "415" without the ".0" you'll get 5 as a result -- one of the operands had a zero scale.

Anyway, good luck and have fun.

"Write beautiful code; then profile that beautiful code and make little bits of it uglier but faster." --The JavaPerformanceTuning.com team, Newsletter 039.
I agree. Here's the link: http://aspose.com/file-tools
subject: Rounding BigDecimal Calculation Yielded Wrong Result