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

1 Answer

0 votes
fn replace_all_digits(num: f64, old_digit: char, new_digit: char) -> f64 {
    // Format the number to a string with 3 decimal places
    let str_num = format!("{:.3}", num);

    // Replace all occurrences of old_digit with new_digit
    let modified_str: String = str_num
        .chars()
        .map(|c| if c == old_digit { new_digit } else { c })
        .collect();

    // Convert the modified string back to f64
    modified_str.parse::<f64>().unwrap_or(0.0)
}

fn main() {
    println!("{:.3}", replace_all_digits(82420.291, '2', '6'));
    println!("{:.3}", replace_all_digits(111.11, '1', '5'));
}



/*
run:

86460.691
555.550

*/



 



answered 15 hours ago by avibootz

Related questions

...