Reputation: 6059
I do a couple of calculations with BigDecimal
, before I return the final result. My calculations contain two divisions. I'm aware of the fact that I should define a scale and rounding mode when calling divide()
. However, since I'm working with currencies, I want to preserve maximum precision as long as possible and only round my final result to two decimal places.
What scale and rounding mode should I apply to intermediate results for maximum precision?
Upvotes: 2
Views: 484
Reputation: 95
I found a helpful website with examples, explanations, and results of providing precision using BigDecimal. It's a quick read.
It show various ways of performing the calculation and provides clear examples: http://java-performance.info/bigdecimal-vs-double-in-financial-calculations/
I hope it helps.
Upvotes: 2
Reputation: 76414
Let's suppose, you do something like (a / b) / c.
I would not calculate (a / b) first. I would rather restructure this into
a / (b * c)
It does not only make intermediary rounding unnecessary, it would be more optimal as well.
(a / b) / c = a / (b * c)
Proof:
(a / b) / c = (a * b^-1) * c^-1 = a * (b^-1 * c^-1) = a * 1 / (b * c) = a / (b * c)
Upvotes: 4
Reputation: 65793
I think any specific answer to your question would probably require some further details on how accurate you need the final results, especially when you are rounding at the end.
I personally would attempt to remove the issue completely and use some form of Rational
object.
How to actually avoid floating point errors when you need to use float? may be of some help.
Upvotes: 1
Reputation: 1441
Usually in physics we take one more digit for intermediate results.
Upvotes: 2