How to replace a digit in a floating-point number by index with C

1 Answer

0 votes
#include <stdio.h>
#include <stdlib.h> // exit
#include <string.h> // strlen
#include <ctype.h> // isdigit

// Function to replace a digit at a given position in a floating-point number
double replaceFloatDigit(double number, size_t position, char newDigit) {
    // Validate that newDigit is indeed a digit
    if (!isdigit((unsigned char)newDigit)) {
        fprintf(stderr, "Replacement must be a digit (0-9).\n");
        exit(EXIT_FAILURE);
    }

    // Convert number to string with enough precision to preserve digits
    char strNum[64];
    snprintf(strNum, sizeof(strNum), "%.10f", number); // Adjust precision as needed

    // Validate position
    if (position >= strlen(strNum)) {
        fprintf(stderr, "Position is out of range for the number string.\n");
        exit(EXIT_FAILURE);
    }

    // Replace the digit (skip if it's a decimal point or minus sign)
    if (strNum[position] == '.' || strNum[position] == '-') {
        fprintf(stderr, "Position points to a non-digit character.\n");
        exit(EXIT_FAILURE);
    }

    strNum[position] = newDigit;

    // Convert back to double
    return strtod(strNum, NULL);
}

int main() {
    double num = 89710.291;
    size_t pos = 2; // position to replace (0-based index)
    char newDigit = '8';

    double result = replaceFloatDigit(num, pos, newDigit);
    printf("Modified number: %.3f\n", result);

    return 0;
}



/*
run:

Modified number: 89810.291

*/



 



answered Nov 17, 2025 by avibootz
edited Nov 17, 2025 by avibootz
...