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

1 Answer

0 votes
#include <iostream>     
#include <string>       
#include <iomanip>      
#include <sstream>      

// Function to replace all occurrences of a digit and then replace the last digit
double replaceAllThenLastDigit(double num, char oldDigit, char newDigit) {
    std::ostringstream oss;

    // Convert the number to a string with fixed-point notation and 3 decimal places
    oss << std::fixed << std::setprecision(3) << num;
    std::string str = oss.str();  // Store the formatted number as a string

    // Replace all occurrences of oldDigit with newDigit
    for (char& ch : str) {
        if (ch == oldDigit) {
            ch = newDigit;
        }
    }

    // Convert the modified string back to a double
    std::istringstream iss(str);
    double result;
    iss >> result;

    return result;  // Return the final modified number
}

int main() {
    // Set output formatting to fixed-point with 3 decimal places
    std::cout << std::fixed << std::setprecision(3);

    // Replace '2' with '6' and then the last digit with '1'
    std::cout << replaceAllThenLastDigit(82420.291, '2', '6') << std::endl;

    // Replace '1' with '5' and then the last digit with '0'
    std::cout << replaceAllThenLastDigit(111.11, '1', '5') << std::endl;
}


 
/*
run:
   
86460.691
555.550
 
*/

 



answered 1 day ago by avibootz
edited 23 hours ago by avibootz

Related questions

...