2017-03-15 196 views
3

在F#中爲項目編碼時,我已經到了要將char轉換爲int的點。即F# - 將char轉換爲int

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

我的問題是,什麼是一個字符爲int轉換無炭轉換爲字符串或其它類型,在字符僅持有一個數字的情況下,最好的方法是什麼?

回答

8

假設您已經驗證了性格和知道這是一個ASCII數字,你可以做到以下幾點:

let inline charToInt c = int c - int '0' 

let c = '3' 
c |> charToInt 

Online Demo

注:如果你最終需要一個float而不是一個int有一個內置的機制:System.Char.GetNumericValue

+1

我想我會堅持'System.Char.GetNumericValue'並將其管道到'int'。謝謝。 –