#### Archived

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

# getting the length of an integer

This topic is 6098 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

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
Convert it to a string.

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

##### Share on other sites
  // 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
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
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
  for ( len = 1; your_integer /= 10; len++);

simple, huh?

___________________________________

##### Share on other sites
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)));

1. 1
Rutin
25
2. 2
3. 3
4. 4
JoeJ
18
5. 5

• 14
• 14
• 11
• 11
• 9
• ### Forum Statistics

• Total Topics
631757
• Total Posts
3002131
×