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,563 questions

56,781 answers

573 users

How to get the Nth digit after the decimal point of a floating-point number in C

1 Answer

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

/*
 * Returns the Nth digit after the decimal point.
 *
 * Parameters:
 *   value    - Floating-point number to inspect.
 *   position - Digit position after the decimal point (1-based).
 *
 * Returns:
 *   The requested digit (0-9).
 *   Returns 0 if the digit does not exist.
 */
int get_nth_decimal_digit(double value, int position)
{
    if (position < 1) {
        return 0;
    }

    /* Buffer large enough for a double representation */
    char buffer[64] = "";

    /*
     * Convert the number to a string.
     * Use a high precision to preserve as many digits as practical.
     */
    snprintf(buffer,
             sizeof(buffer),
             "%.15f",
             fabs(value));

    /* Find the decimal point */
    char *decimal_point = strchr(buffer, '.');

    if (decimal_point == NULL) {
        return 0;
    }

    /* Move to the requested digit */
    decimal_point += position;

    /* Digit does not exist */
    if (*decimal_point == '\0') {
        return 0;
    }

    /* Convert character to integer */
    return *decimal_point - '0';
}

int main(void)
{
    double number = 123.456789;

    printf("Number: %.6f\n\n", number);

    for (int i = 1; i <= 6; ++i) {
        printf("%d digit after decimal = %d\n",
               i,
               get_nth_decimal_digit(number, i));
    }

    printf("\nAdditional Examples\n");
    printf("-------------------\n");

    printf("123.456789, position 4 -> %d\n",
           get_nth_decimal_digit(123.456789, 4));

    printf("-98.7654, position 2 -> %d\n",
           get_nth_decimal_digit(-98.7654, 2));

    printf("1.2, position 5 -> %d\n",
           get_nth_decimal_digit(1.2, 5));

    return 0;
}


/*
run:

Number: 123.456789

1 digit after decimal = 4
2 digit after decimal = 5
3 digit after decimal = 6
4 digit after decimal = 7
5 digit after decimal = 8
6 digit after decimal = 9

Additional Examples
-------------------
123.456789, position 4 -> 7
-98.7654, position 2 -> 6
1.2, position 5 -> 0

*/

 



answered 1 day ago by avibootz

Related questions

...