Search code examples
f#functional-programming

F# - Convert a char to int


While coding in F# for a project, I have come to a point where I want to convert a char to an int. I.e.

let c = '3'
c |> int //this will however give the ascii value of 3 I believe

My question is, what is the best way to convert a single char to an int without converting the char to a string or another types, in a case where the char only holds a digit?


Solution

  • Assuming you've validated the character and know that it's an ASCII digit, you can do the following:

    let inline charToInt c = int c - int '0'
    
    let c = '3'
    c |> charToInt
    

    Online Demo

    N.b. if you ultimately need a float rather than an int there is a built-in mechanism: System.Char.GetNumericValue