How to get the first digit of a float number in C#

2 Answers

0 votes
using System;

class Program
{
    static int GetFirstDigit(float x)
    {
        string s = x.ToString();
        
        return int.Parse(s.Substring(0, 1));
    }

    static void Main()
    {
        float f = 872.1459f;

        Console.Write(GetFirstDigit(f));   
    }
}


/*
run:

8

*/

 



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

class Program
{
    static int GetFirstDigit(float x)
    {
        int int_part = (int)x;
        int total_digits_minus_one = (int)Math.Log10(int_part);
        int first_digit = (int)(int_part / Math.Pow(10, total_digits_minus_one));
        
        return first_digit;
    }

    static void Main()
    {
        float f = 972.1459f;

        Console.WriteLine(GetFirstDigit(f));   
    }
}



/*
run:

9

*/

 



answered Aug 29, 2019 by avibootz
edited Sep 15 by avibootz
...