How to convert a string to an int in F#

Date: 2024-05-29 | create | tech | fsharp |

In webdev there's a lot of raw string to value conversion. This is because, like it or not, most network communication is done via raw strings. To be able to leverage the power of F#'s type system, we need to safely convert these into the type our domain expects and handle errors if and when they occur.

In this post we'll explore a simple method for safely parsing an int from a raw string in F#.

Converting a string to an int in F#

For this example we'll be using the built-in Int32.TryParse method. I like this for a few reasons:

  • Built-in
  • Uses value-based errors (and thus expects that errors can happen - they will)
  • Nice-ish API

You can use the function directly but I like to wrap it in an option because I think it pipelines a little better.


let tryParseInt 
    (s: string)
    : int option 
    let success, result = Int32.TryParse s
    match success with 
    | true -> Some result 
    | false -> None

You can try it out in this example Replit.

Alternative Approaches

There are probably many other ways to do this, each with their own pros / cons.

Some popular ones can make this conversion easier if you know for a fact that your string is parseable to an int. I would argue that if you have a string you cannot know for sure that it is int parseable so you should just use the error-safe method but to each their own.

Some alternative ways to convert that will fail hard (throw) if not int parseable:

  • s |> int - uses built-in int function to convert string to int
  • Int32.Parse - Same API we used above just converts directly or fails hard


There are infinite ways to do any one thing - this is just a method I've found works well.

Q: How are you doing type conversions in F#?

If you liked this post you might also like:

Want more like this?

The best / easiest way to support my work is by subscribing for future updates and sharing with your network.