|
|
|
|
|
by wazokazi
1248 days ago
|
|
I would encapsulate the set of supported operations in a class along with the rounding mode and scale. Something like:
------ class MathOps{
public MathOps(RoundingMode mode, int scale) {
this.mode = mode;
this.scale = scale;
}
....
public BigDecimal add(BigDecimal x, BigDecimal y){
return x.add(y).setScale(scale, roundingMode);
}
....
public BigDecimal divide(BigDecimal num, BigDecimal denom) {
return num.divide(denom, scale, roundingMode).setScale(scale, roundingMode);
}
...
}
-----
You can then either create a new instance when you need to perform a math operation or just create a singleton instance if scale and rounding mode are always the same.For financial calculations in US, I would recommend using RoundingMode.HALF_EVEN. From the docs
"Rounding mode to round towards the "nearest neighbor" unless both neighbors are equidistant, in which case, round towards the even neighbor. Behaves as for RoundingMode.HALF_UP if the digit to the left of the discarded fraction is odd; behaves as for RoundingMode.HALF_DOWN if it's even. Note that this is the rounding mode that statistically minimizes cumulative error when applied repeatedly over a sequence of calculations. It is sometimes known as "Banker's rounding," and is chiefly used in the USA. " |
|