Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 722
Tomb_Raider_Legend Avatar asked Mar 15 '17 20:03

Tomb_Raider_Legend


2 Answers

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

like image 188
ildjarn Avatar answered Oct 25 '22 03:10

ildjarn


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
like image 24
Marcelino Galarza Avatar answered Oct 25 '22 01:10

Marcelino Galarza