Reputation: 32083
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
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
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