17

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?

2
  • maybe like NUMBER(10,2) (Oracle basis, though)? Jun 5, 2012 at 14:43
  • We use sybase, so not really sure about Oracle. I'm just trying to build a field validator in java with an if statement to test and make sure the value being submitted doesn't exceed 10,2. Jun 5, 2012 at 14:47

1 Answer 1

29

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;        
}
3
  • This is exactly what I was looking for, I completely missed the scale and precision in the api. Shame on me. Jun 5, 2012 at 16:12
  • @Teetoo, @George - Don't you think in if block - scale = 0; and precision -= scale; should be swapped?
    – Premraj
    Dec 20, 2012 at 8:34
  • @Teetoo I did the change, review it :)
    – Premraj
    Dec 20, 2012 at 8:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.