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,914 questions

51,847 answers

573 users

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 Nov 17, 2025 by avibootz
edited Nov 18, 2025 by avibootz

Related questions

...