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