Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,181 questions

56,073 answers

573 users

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 2 days ago 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 2 days ago by avibootz

Related questions

...