Alex Rivera | Logout

How can you get the first digit in an int (C#)?

Asked 2009-03-31T14:45:05.720
90

In C#, what's the best way to get the 1st digit in an int?

The method I came up with is to:

  • turn the int into a string,
  • get the 1st char of the string, and
  • turn the char into an int.

Like:

int start = Convert.ToInt32(curr.ToString().Substring(0, 1));

While this does the job, it feels like there is probably a good, simple, math-based solution to such a problem. String manipulation feels clunky.

Edit:
Irrespective of speed differences, mystring[0] instead of Substring() is still just string manipulation

Edit
Report

2 Answers

131

Here's how

int i = Math.Abs(386792);
while(i >= 10)
    i /= 10;

and i will contain what you need

answered 2009-03-31T14:50:26.050
0
int i = 4567789;
int digit1 = int.Parse(i.ToString()[0].ToString());
answered 2010-07-01T03:33:05.720

Your Answer