Why does .parse () convert "42" to f64 but fail to convert "42.0" to i32?

Why and how does this line work:

let guess: f64 = "42".parse().expect("Not a number!");

But is that not so?

let guess: i32 = "42.0".parse().expect("Not a number!");

Result:

thread 'main' panicked at 'Not a number!: ParseIntError { kind: InvalidDigit }'

What is the correct way to parse "float" & str to an integer?

Update:

I found this to work:

let guess: i32 = "42.0".parse::<f64>().expect("Not a number!") as i32;

However, I do not understand the mechanics of how this works, and if this is the right way to do this?

+4
source share
1 answer

What you cause is, in fact let guess: i32 = "42.0".parse::<i32>();.

However, "42.0"this is not a correct representation i32.

According to the documentation :

parse , . , parse , "turbofish": ::<>. , .

, , , float:

"42.0".parse::<f64>()
+4

Source: https://habr.com/ru/post/1688930/


All Articles