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

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

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

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,971 questions

51,913 answers

573 users

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

2 Answers

0 votes
#include <stdio.h>
#include <math.h>   // 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 = fabs(num);

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

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

    // Floor to get the integer digit
    return (int)floor(num);
}

int main(void) {
    double value = 48724.928;

    int firstDigit = getFirstDigit(value);
    printf("First digit: %d\n", firstDigit);

    firstDigit = getFirstDigit(0.9761);
    printf("First digit: %d\n", firstDigit);

    return 0;
}


/*
run:

First digit: 4
First digit: 9

*/



 



answered Nov 17, 2025 by avibootz
0 votes
#include <stdio.h>
#include <math.h>
#include <ctype.h> // isdigit

// Function to extract the first digit of a floating-point number
int getFirstDigit(double num) {
    char buffer[64];

    num = fabs(num); // handle negative numbers

    // Convert number to string
    snprintf(buffer, sizeof(buffer), "%.15g", num); // Use %.15g to avoid scientific notation

    // Find first digit character
    for (int i = 0; buffer[i] != '\0'; ++i) {
        if (isdigit((unsigned char)buffer[i])) {
            return buffer[i] - '0';
        }
    }

    return -1; // error case
}

int main() {
    double value = 48724.928;

    int firstDigit = getFirstDigit(value);
    printf("First digit: %d\n", firstDigit);

    firstDigit = getFirstDigit(0.9761);
    printf("First digit: %d\n", firstDigit);

    return 0;
}



/*
run:

First digit: 4
First digit: 0

*/



 



answered Nov 17, 2025 by avibootz
...