4

Why and how does this line work:

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

But this does not?

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

Resulting in:

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

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

Update:

I found this to work:

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

However I don't understand the mechanics of how it works and if it is the correct way to do it?

Greg
  • 8,175
  • 16
  • 72
  • 125

1 Answers1

6

What you're calling is actually let guess: i32 = "42.0".parse::<i32>();.

However, "42.0" is not a correct representation of an i32.

According to the documentation:

Because parse is so general, it can cause problems with type inference. As such, parse is one of the few times you'll see the syntax affectionately known as the 'turbofish': ::<>. This helps the inference algorithm understand specifically which type you're trying to parse into.

The correct solution which you've already found is indeed to hint at the parser that the string is the representation of a float:

"42.0".parse::<f64>()
Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
SirDarius
  • 41,440
  • 8
  • 86
  • 100
  • I would note that annotating the type of the left hand side is generally sufficient to avoid using the turbofish operator (and more concise). Here it's really an edge case, wanting to parse as a float and truncate the data. – Matthieu M. Nov 08 '17 at 11:39
  • 1
    Note that given the string `"42.1"`, the proposed solution will silently truncate it to `42`, which may or may not be desirable depending on your application. In some cases, you may want to check that the parsed float really represents an integer before converting. – Jmb Nov 08 '17 at 13:30
  • 2
    @Jmb Which is why OP should use `trunc`, `ceil` or `floor` to express their intent explicitely, instead on relying on the default behaviour (which is currently equivalent to trunc, see https://stackoverflow.com/a/37508518/393701). – SirDarius Nov 08 '17 at 14:49