Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a string represents a floating-point number?

Tags:

rust

Is there a way in Rust to check if a string contains a floating-point number without resorting to regexes?

Something giving similar result as this (used regex: https://regex101.com/r/pV6wJ6/2)

re = Regex::new(r#"^-?(0|[1-9]\d*)(\.\d+)?$"#).unwrap()
assert_eq!(is_number(some_string), re.is_match(some_string))
like image 842
Jakub Avatar asked Oct 03 '15 11:10

Jakub


People also ask

How do you convert a string number to a floating point number?

We can convert a string to float in Python using the float() function. This is a built-in function used to convert an object to a floating point number. Internally, the float() function calls specified object __float__() function.

How do you check if a variable is a float?

The is_float() function checks whether a variable is of type float or not. This function returns true (1) if the variable is of type float, otherwise it returns false.

Is 3.14 a string integer or float value?

3.14 is a floating point number, or float for short. "Hello" is a string.


1 Answers

You didn't give any examples, so I'll use "1.23" and "bob".

Just try to parse it:

fn main() {
    let num = "1.23".parse::<f64>();
    match num {
        Ok(val) => println!("Yes, it was a number ({})", val),
        Err(why) => println!("Doesn't look like a number ({})", why),
    }
}

str::parse can return any type that implements the FromStr trait. In this case, f64 defines ParseFloatError as the errors possible when converting a string to a floating point number.

If you just care if it is a number or not, you can use is_ok:

fn main() {
    let is_num = "1.23".parse::<f64>().is_ok();
    println!("Is a number: {}", is_num);
}
like image 191
Shepmaster Avatar answered Oct 29 '22 02:10

Shepmaster