Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 541
Code Junkie Avatar asked Jun 05 '12 14:06

Code Junkie


People also ask

How do you check BigDecimal precision?

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.

What is scale and precision in BigDecimal?

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.

How do I find the number of decimal places in BigDecimal?

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.


1 Answers

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;        
}
like image 147
tofcoder Avatar answered Sep 25 '22 09:09

tofcoder