Search code examples
javavalidationdecimalbigdecimal

Best way to check minor unit of BigDecimal in Java


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:

  • 5 --> valid
  • 5.0 --> valid
  • 5.00 --> valid
  • 5.000 --> valid
  • 5.1 --> valid
  • 5.11 --> valid
  • 5.111 --> NOT valid
  • 5.110 --> valid

Code should be something like:

public void isValid(BigDecimal amountToCheck, BigDecimal minorUnit) {
    //TODO
}

Solution

  • 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;
    }