String to int conversion using toInt function

toInt can fail in parsing. You need to check it using a case statement:

case toInt str of
  Err msg -> ... -- do something with the error message
  Ok val -> ... -- val is an Int which you can add

More about Result here


Here's how to supply the conversion with a default value in case the parsing fails.

String.toInt "5" |> Result.toMaybe |> Maybe.withDefault 0

The integer can also be pulled out using

Result.withDefault 0 (String.toInt "2")

You can read more about it here


According to the Elm String reference documentation, if you are extracting a number from some raw user input, you will typically want to use Result.withDefault to handle bad data in case parsing fails. You can chain this operation using pipes for cleaner code:

String.toInt "5" |> Result.withDefault 0

Tags:

Elm