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

1 Answer

0 votes
use std::error::Error;

/// Replace a digit at a given position in a floating-point number.
fn replace_float_digit(number: f64, position: usize, new_digit: char) -> Result<f64, String> {
    // Validate that new_digit is indeed a single digit
    if !new_digit.is_ascii_digit() {
        return Err("Replacement must be a digit (0-9).".to_string());
    }

    // Convert number to string with fixed precision (10 decimal places)
    let str_num = format!("{:.10}", number);

    // Validate position
    if position >= str_num.len() {
        return Err("Position is out of range for the number string.".to_string());
    }

    // Ensure position points to a digit
    let ch = str_num.chars().nth(position).unwrap();
    if ch == '.' || ch == '-' {
        return Err("Position points to a non-digit character.".to_string());
    }

    // Replace digit
    let mut chars: Vec<char> = str_num.chars().collect();
    chars[position] = new_digit;
    let modified: String = chars.into_iter().collect();

    // Convert back to float
    match modified.parse::<f64>() {
        Ok(result) => Ok(result),
        Err(_) => Err("Conversion failed.".to_string()),
    }
}

fn main() -> Result<(), Box<dyn Error>> {
    let num = 89710.291;
    let pos = 2;        // 0-based index
    let new_digit = '8';

    match replace_float_digit(num, pos, new_digit) {
        Ok(result) => {
            // Print result with 3 decimal places
            println!("Modified number: {:.3}", result);
        }
        Err(e) => {
            eprintln!("Error: {}", e);
        }
    }

    Ok(())
}



/*
run:

Modified number: 89810.291

*/



answered Nov 17, 2025 by avibootz
...