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?
precision() method returns the precision of this BigDecimal. The precision is the number of digits in the unscaled value. The precision of a zero value is 1.
A BigDecimal consists of an arbitrary precision integer unscaled value and a 32-bit integer scale. If zero or positive, the scale is the number of digits to the right of the decimal point. If negative, the unscaled value of the number is multiplied by ten to the power of the negation of the scale.
math. BigDecimal. scale() is an inbuilt method in java that returns the scale of this BigDecimal. For zero or positive value, the scale is the number of digits to the right of the decimal point.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With