How to extract the first digit from a floating-point number in C++

1 Answer

0 votes
#include <iostream>
#include <cmath>    // For fabs, floor

// Function to extract the first digit of a floating-point number
int getFirstDigit(double num) {
    // Handle zero explicitly
    if (num == 0.0) {
        return 0;
    }

    // Work with absolute value to ignore sign
    num = std::fabs(num);

    // Shift decimal point until number >= 1
    while (num < 1.0) { // Run when num < 1.0
        num *= 10.0;
    }

    // Shift until number < 10
    while (num >= 10.0) { // Run when num > 10.0
        num /= 10.0;
    }

    // Floor to get the integer digit
    return static_cast<int>(std::floor(num));
}

int main() {
    double value = 48724.928;

    int firstDigit = getFirstDigit(value);
    std::cout << "First digit: " << firstDigit << "\n";
    
    firstDigit = getFirstDigit(0.9761);
    std::cout << "First digit: " << firstDigit << "\n";
}


/*
run:

First digit: 4
First digit: 9

*/

 



answered 5 hours ago by avibootz
...