Search code examples
javabigdecimal

How do I validate precision and scale with BigDecimal?


I'm trying to validate the precision and scale of a big decimal.

I'm looking to validate a big decimal doesn't exceed a precision of 10 or a scale of 2. I tried doing a maxlength so the value wouldn't be violating my db length constraints, but was unable to get that working either. Could someone kindly point me in the direction to resolving this issue?


Solution

  • The BigDecimal class has three methods which could be of interest for this:

    • precision(), which returns the number of digits for the unscaled value (for instance, for the number 123.45, the precision returned is 5)
    • scale(), which returns the number of digits after the decimal separator when positive (scale() can be negative, in this case, the unscaled value of the number is multiplied by ten to the power of the negation of the scale. For example, a scale of -3 means the unscaled value is multiplied by 1000),
    • stripTrailingZeros(), which returns a BigDecimal with all trailing zeros removed from the representation.

    For instance, to compute the precision and scale for a given BigDecimal b, we can write something like that:

    BigDecimal noZero = b.stripTrailingZeros();
    int scale = noZero.scale();
    int precision = noZero.precision();    
    if (scale < 0) { // Adjust for negative scale
        precision -= scale;
        scale = 0;        
    }