How to convert user input String to Floating point and loop error message prompt

I am trying to get user input expecting floating point number and show error prompt using match until number(s) being used. I also want to catch the floating value outside the loop to use for calculation.

I used stdin to get user input and stored in a value variable created from String::new(). Because value stored input from user, it was String type. I used value.trim().parse::<f32>() to convert it into f32 type. It seems i am doing something wrong.
During compile time i get mismatched type error.
It says: expected f32 found String
Here is my code:

fn main() {
    println!("\nPlease Input the Value you want to convert: ");
    let value:f32 = loop{
        let mut value = String::new();
            .read_line(&mut value)
            .expect("Failed to read line");
        match value.trim().parse::<f32>(){
            Ok(num) => break value, //edited: mistake was here, should be num not value.Thanks to H2CO3
            Err(_) => {
                println!("please input value in number(s).");}
    println!("Thank You, I have the value: {value}.")

value is a String. The parsed number is in num. You want break num instead of break value.


:slight_smile: thanks again. Sorry for the trouble. it was a blunder. Its 2am and i am getting brain dead. Thanks a lot. goodnight

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.