Tiny
Tiny

Reputation: 27899

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?

Upvotes: 2

Views: 2986

Answers (2)

Eich
Eich

Reputation: 3788

You can convert it to a string and count the number of characters:

...
BigInteger bi = new BigInteger("12345678");
Integer numberOfDigits = bi.abs().toString().length();
boolean isValid=numberOfDigits>=minNumberOfDigits && numberOfDigits<=maxNumberOfDigits;

Upvotes: 4

Joe Elleson
Joe Elleson

Reputation: 1373

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.

Upvotes: 6

Related Questions