简体   繁体   中英

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. Ie

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

Nb 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

先转换成字符串:

c |> sprintf "%c" |> int

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM