Ky -
Ky -

Reputation: 32083

How can I get the max decimal value of n-digit number in Java?

In our code, we have the maximum number of digits allowed (say, 8) in a decimal (as in base 10) number. How can I use this number to see if a possible value is within that range (0 to 99,999,999)?

If we were working with binary numbers, I'd do something like:

value < 1<<(MAX + 1)

but of course that won't work for decimal. I also considered something like:

Long.toString(value).length() < MAX

but that seems much too heavy.

Upvotes: 1

Views: 3570

Answers (4)

smac89
smac89

Reputation: 43078

Use log base 10 to get the number of digits in a base 10 number

if ((int)(Math.log10(value) + 1) <= MAX) {
    ...
}

If you don't have access to log10, you can use normal log to do this:

int length = (int)(Math.log(value) / Math.log(10)) + 1;
if (length <= MAX) {
    ...
}

Note this also works for any base, so using the second method above, you can replace the 10 with any base and you have the length of that number in the given base

Upvotes: 3

radiaph
radiaph

Reputation: 4081

if (value >= 0 && value < Math.pow(10, MAX))

Upvotes: 8

Anil
Anil

Reputation: 588

Would this work? val>=0 && (value/1000000000)==0 ?

Upvotes: 0

BRPocock
BRPocock

Reputation: 13914

You can take 10 to the (nth) power;

  value < (Math.pow (10, num_digits))

… for positive integer fixnums; if you're more concerned with magnitude than sign, perhaps use the absolute value:

  Math.abs(value) < (Math.pow (10, num_digits))

This, of course, doesn't apply to floating-point or BigDecimal values, but the same (analogous, using method calls) works for arbitrarily large bignums using BigInteger.

Upvotes: 1

Related Questions