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?
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
If you're trying to convert a -> 0, b -> 1, ....., z -> 26. Then you could do this
let let2nat (letter : char) = int letter - int 'a'
If you just want the ascii you can do this
let let2ascii (let2ascii : char) = int let2ascii
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With