How to replace all occurrences of a specific digit in a floating-point number with C

1 Answer

0 votes
#include <stdio.h>
#include <string.h>
#include <stdlib.h> // strtod
 
double replaceAllDigits(double num, char oldDigit, char newDigit) {
    char buffer[64];
    snprintf(buffer, sizeof(buffer), "%.3f", num);  // Convert to string with high precision
 
    for (int i = 0; buffer[i] != '\0'; i++) {
        if (buffer[i] == oldDigit) {
            buffer[i] = newDigit;
        }
    }
 
    return strtod(buffer, NULL);  // Convert modified string back to double
}
 
int main() {
    printf("%.3f\n", replaceAllDigits(82420.291, '2', '6'));
    printf("%.3f\n", replaceAllDigits(111.11, '1', '5'));
     
    return 0;
}
 
 
 
/*
run:
   
86460.691
555.550
   
*/

 



answered 20 hours ago by avibootz
edited 13 hours ago by avibootz

Related questions

...