#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
*/