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

1 Answer

0 votes
#include <iostream>
#include <cmath>

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

    Method:
    1. Use fabs() to ensure negative values behave consistently.
    2. Multiply by 10 to shift the first decimal digit into the integer part.
    3. Apply floor() to avoid rounding issues.
    4. Use modulo 10 to isolate the digit.

    This approach is numeric, efficient, and avoids string conversion.
*/
int first_digit_after_decimal(float value) {
    return static_cast<int>(std::floor(std::fabs(value) * 10)) % 10;
}

int main() {
    float f = 983.6571f;

    int n = first_digit_after_decimal(f);

    std::cout << n;
}


/*
run:

6

*/

 



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

Related questions

...