Check if string is numeric


#1

How can check if a string is numeric?
for example I want to check if the string “-23.55” or “123” is numeric.

In PHP i could just use is_numeric("-23.55"); and it will return true. But I cannot found anything similar in rust.


#2

You can use s.parse::<f64>().is_ok().


#3

thanks almost got it working but how come this code is working:

let s1 = String::from("12.44");
let test = s1.parse::<f64>();

 match test {
    Ok(ok) => println!("it is a decimal ({})", ok),
    Err(e) => println!("not a decimal ({})", e), 
}  

But when i try use this code with stdin i get error.

let mut number = String::new();
io::stdin().read_line(&mut number);

let test = &number.parse::<f64>();
     match test {
        Ok(ok) => println!("it is a decimal ({})", ok),
        Err(e) => println!("not a decimal ({})", e), 
    }

#4

It may contain the trailing newline character, you can try:

number.trim().parse::<f64>();