#### Archived

This topic is now archived and is closed to further replies.

# getting the length of an integer

## Recommended Posts

Nibbles    569
Hi, how would I go about getting the length (number of digits) in an integer, and then say find out what the first digit is? preferably in java, but C is ok too. Thanks, Scott Email Website
"If you try and don't succeed, destroy all evidence that you tried." Edited by - wojtos on November 5, 2001 3:07:20 AM

##### Share on other sites
Guest Anonymous Poster
Convert it to a string.

then the number of letters = the length and then first letter is the first number

##### Share on other sites
S1CA    1418
  // this is the input integerint some_integer = 265471;// length of the number in digitsint length = 0;// first digit of the numberint first_digit;do{ first_digit = some_integer; some_integer = some_integer / 10; ++length;}while (some_integer != 0);

Surely you remember maths from junior school?:

1s, 10s, 100s, 1000s, 10000s etc...

It keeps dividing by 10 until the integer becomes a fraction (i.e. less than 1). Because the number is an integer, any fraction will come out as a 0.

Small gotcha is for a negative number, the first digit will also be negative (you may actually want that - if not, do an abs(x) on it).

--
Simon O''''Connor
Creative Asylum Ltd
www.creative-asylum.com

##### Share on other sites
GAG34    122
One simple way to find the length of an integer is to use log10().

int x = 65837;

int length = log10(x)+1;

I don''t know how efficient that is, but it is easy to understand.

##### Share on other sites
invective    118
in java convert to Integer class and call toString(). get the length of the string. adjust for minus sign as necessary.

int number, numberOfDigits;
Integer tempNumber;
string tempString;

tempNumber = new Integer ( Math.abs ( number ) );
tempString = tempNumber.toString ();
numberOfDigits = tempString.length ();

First digit is first char in string, or:

tempString.chatAt (0);

##### Share on other sites
bishop_pass    109
  for ( len = 1; your_integer /= 10; len++);

simple, huh?

___________________________________

##### Share on other sites
thuned    122
i don''t think java has the log10 function...

try base converting

numdigs = Math.log(num) / Math.log(10) + 1;

then

firstdig = (int)(num/(Math.pow(10,numdigs-1)));