I would like to check whether a single char is an ASCII number ('1' - '9') or a period ('.'). What is the best way to do that in Rust? I know that is_digit(10) is for numbers but how do I do it for numbers or periods (.)?
I would like to check whether a single char is an ASCII number ('1' - '9') or a period ('.'). What is the best way to do that in Rust? I know that is_digit(10) is for numbers but how do I do it for numbers or periods (.)?
One small catch of char::is_numeric might be that it matches on more than ASCII 0..=9, e.g:
'½'.is_numeric() == true
There's char::is_ascii_digit if you only want to match on ASCII 0..=9.
The latter is implemented with the matches! macro. You can also use the macro for your use case, e.g:
if matches!(c, '0'..='9' | '.') {
// Character is ASCII digit '0' up to and including '9' or '.'
}
Use is_numeric OR'd with an '.' equality check:
fn is_numeric_or_period(c: char) -> bool {
char::is_numeric(c) || c == '.'
}
Note: is_numeric matches all numeric unicode characters, and will behave identically to is_ascii_digit for ASCII strings, but if you're working with unicode strings and only want to match on ASCII numeric characters then refer to @Jason's answer.