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

2 Answers

0 votes
#include <stdio.h>
#include <math.h>

/*
    first_digit_after_decimal_post:
    --------------------------------
    Extracts the first digit after the decimal point using arithmetic only.

    Steps:
    1. fabs(value) ensures negative numbers behave correctly.
    2. Multiply by 10 to shift the first decimal digit into the integer part.
    3. floor(...) removes floating-point noise.
    4. Cast to int and take % 10 to isolate the digit.
*/
int first_digit_after_decimal_post(float value) {
    int n = (int)(floor(fabs(value) * 10)) % 10;
    return n;
}


int main() {
    float f = 3.2871f;

    int digit = first_digit_after_decimal_post(f);

    printf("%d", digit);

    return 0;
}


/*
run:

2

*/

 



answered Aug 24, 2019 by avibootz
edited Sep 15 by avibootz
0 votes
#include <stdio.h>
#include <math.h>

/*
    get_first_decimal_digit:
    ------------------------
    Extracts the first digit after the decimal point from a float.

    Algorithm:
    1. Separate the fractional part using modf().
    2. Multiply the fractional part by 10.
    3. Truncate to int to get the first digit.

    This avoids string conversion and keeps the logic numeric and efficient.
*/
int first_digit_after_decimal_post(double value) {
    double integer_part = 0.0;
    double fractional_part = modf(value, &integer_part);  // fractional_part is in [0,1)
    int digit = (int)(fractional_part * 10);              // shift and truncate
    
    return digit < 0 ? -digit : digit;                    // handle negative numbers
}

int main(void) {
    double number = 123.456;  // example input

    int digit = first_digit_after_decimal_post(number);

    printf("Number: %.3f\n", number);
    printf("First digit after decimal: %d\n", digit);

    return 0;
}


/*
run:

Number: 123.456
First digit after decimal: 4

*/

 



answered Sep 15 by avibootz

Related questions

...