0

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
}
victorio
  • 6,224
  • 24
  • 77
  • 113
  • 1
    Why would you use `BigDecimal minorUnit`? Does the value of `0.01` change? If yes, why BigDecimal and not a simple `int` specifying how many decimal places there can be? – Pijotrek Aug 23 '17 at 12:49
  • These are good questions, but the thing is that this is how they implemented here where I work the minor unit thingy, so I need to get a solution by this way. – victorio Aug 24 '17 at 07:31

1 Answers1

1

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;
}
Arnaud
  • 17,229
  • 3
  • 31
  • 44