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

2 Answers

0 votes
using System;

/*
    firstDigitAfterDecimal:
    -----------------------
    Extracts the first digit after the decimal point from a floating‑point number.

    Method:
    1. Convert the number to a string using ToString().
    2. Locate the decimal point.
    3. Take the character immediately after it.
    4. Convert that character back to an integer.

    This approach is simple, expressive, and uses familiar built‑in methods.
*/

class Program
{
    static int firstDigitAfterDecimal(float value)
    {
        string s = value.ToString();
        int dotIndex = s.IndexOf(".");

        return int.Parse(s.Substring(dotIndex + 1, 1));
    }
    
    static void Main()
    {
        float f = 872.2459f;

        int digit = firstDigitAfterDecimal(f);

        Console.Write(digit);
    }
}


/*
run:

2

*/

 



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

/*
    FirstDigitAfterDecimal:
    -----------------------
    Extracts the first digit after the decimal point from a floating‑point number.

    Method:
    1. Take the absolute value to ensure consistent behavior for negatives.
    2. Multiply by 10 to shift the first decimal digit into the integer part.
    3. Apply Math.Floor to avoid rounding issues.
    4. Use modulo 10 to isolate the digit.

    This keeps the logic numeric, efficient, and clear.
*/
class Program
{
    static int FirstDigitAfterDecimal(float value)
    {
        return (int)(Math.Floor(Math.Abs(value) * 10)) % 10;
    }    
    static void Main()
    {
        float f = 23.7846f;

        int digit = FirstDigitAfterDecimal(f);

        Console.Write(digit);
    }
}


/*
run:

7

*/

 



answered Aug 31, 2019 by avibootz
edited Sep 15 by avibootz

Related questions

...