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

51,859 answers

573 users

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

1 Answer

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

// 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 (newDigit < '0' || newDigit > '9') {
        throw std::invalid_argument("Replacement must be a digit (0-9).");
    }
 
    // Convert number to string with enough precision to preserve digits
    std::ostringstream oss;
    oss << std::fixed << std::setprecision(10) << number; // Adjust precision as needed
    std::string strNum = oss.str();
 
    // Validate position
    if (position >= strNum.size()) {
        throw std::out_of_range("Position is out of range for the number string.");
    }
 
    // Replace the digit (skip if it's a decimal point or minus sign)
    if (strNum[position] == '.' || strNum[position] == '-') {
        throw std::invalid_argument("Position points to a non-digit character.");
    }
    strNum[position] = newDigit;
 
    // Convert back to double
    return std::stod(strNum);
}
 
int main() {
    try {
        double num = 89710.291;
        size_t pos = 2; // position to replace (0-based index
        char newDigit = '8';
 
        double result = replaceFloatDigit(num, pos, newDigit);
        std::cout << "Modified number: " << std::setprecision(10) << result << "\n";
 
    } catch (const std::exception &e) {
        std::cerr << "Error: " << e.what() << "\n";
    }
}
 
 
/*
run:
 
Modified number: 89810.291
 
*/

 



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