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 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
...