How to get the first digit of int number in C#

4 Answers

0 votes
using System;

class Program
{
    static void Main() {
        int i = 97253;
        string s = i.ToString();
        
        Console.WriteLine(s[0]);
    }
}



/*
run:

9

*/

 



answered Aug 29, 2019 by avibootz
0 votes
using System;

class Program
{
    static void Main() {
        int i = 97253;
        string s = i.ToString();
        int num = (int)s[0] - 48;
        
        Console.WriteLine(num);
    }
}



/*
run:

9

*/

 



answered Aug 29, 2019 by avibootz
0 votes
using System;

class Program
{
    static void Main() {
        int i = 87253;
        string s = i.ToString();
        int num = s[0] - '0';
        
        Console.WriteLine(num);
    }
}



/*
run:

8

*/

 



answered Aug 29, 2019 by avibootz
0 votes
using System;

class Program
{
    static void Main() {
        int i = 87253;
        int first_digit = i;
 
        while(first_digit >= 10) {
            first_digit = first_digit / 10;
        }

        Console.WriteLine(first_digit);
    }
}



/*
run:

8

*/

 



answered Aug 29, 2019 by avibootz

Related questions

1 answer 176 views
1 answer 142 views
2 answers 223 views
2 answers 165 views
1 answer 146 views
1 answer 136 views
1 answer 146 views
...