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))
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.
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.
3.14 is a floating point number, or float for short. "Hello" is a string.
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With