I have a minor unit setup for amounts, which is: 0.01
It means the amounts are allowed to have maximum 2 decimals.
What could be the best and easiest validation check in Java for these examples:
Code should be something like:
public void isValid(BigDecimal amountToCheck, BigDecimal minorUnit) {
//TODO
}
The biggest part of this answer is taken from Determine Number of Decimal Place using BigDecimal.
So basically you have one method giving you the number of decimals (excluding trailing 0
decimals) :
int getNumberOfDecimalPlaces(BigDecimal bigDecimal) {
String string = bigDecimal.stripTrailingZeros().toPlainString();
int index = string.indexOf(".");
return index < 0 ? 0 : string.length() - index - 1;
}
Then you call it to fit your needs :
public boolean isValid(BigDecimal amountToCheck, BigDecimal minorUnit) {
return getNumberOfDecimalPlaces(amountToCheck) <= getNumberOfDecimalPlaces(minorUnit);
}
Or as the comment by @Pijotrek suggests :
public boolean isValid(BigDecimal amountToCheck, int maxDecimals ) {
return getNumberOfDecimalPlaces(amountToCheck) <= maxDecimals;
}