Search code examples
javabigintegerbigdecimal

How to obtain the precision of BigInteger in Java


I'm implementing a custom validator in my web application that can validate a BigInteger property of a bean. This property is mapped to a Number(8, 0) type of Oracle table.

Like BigDecimal, I don't see a method for BigInteger that can return the precision of a given number.

Basically, I'm first converting a BigInteger value to BigDecimal to obtain its precision like the following (It is just for a demonstration).

int minPrecision=1;
int maxPrecision=8;

BigInteger bigInteger=new BigInteger("12345");
BigDecimal bigDecimal=new BigDecimal(bigInteger, 0);

int precision=bigDecimal.precision();
boolean isValid=precision>=minPrecision && precision<=maxPrecision;

System.out.println(isValid+" : "+precision);

Does BigInteger provide a precise way to return the precision of its value?


Solution

  • There is no precision method on a BigInteger because the concept of precision does not make sense for an Integer. BigInteger represents Integers of arbitrary size, as opposed to BigDecimal which represents exact decimal representations of floating point numbers and therefore have an associated precision.