F# - 将char转换为int

Tom*_*end 8 f# functional-programming

在F#中为项目编码时,我已经达到了将char转换为int的程度.即

let c = '3'
c |> int //this will however give the ascii value of 3 I believe
Run Code Online (Sandbox Code Playgroud)

我的问题是,在char只保存数字的情况下,将char转换为字符串或其他类型的单个char转换为int的最佳方法是什么?

ild*_*arn 14

假设您已经验证了该字符并知道它是一个ASCII数字,您可以执行以下操作:

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

let c = '3'
c |> charToInt
Run Code Online (Sandbox Code Playgroud)

Online Demo

Nb,如果你最终需要一个float而不是int一个内置机制:System.Char.GetNumericValue

  • 我想我会坚持使用`System.Char.GetNumericValue`并将它管道化为`int`.谢谢. (2认同)
  • ```c |> System.Globalization.CharUnicodeInfo.GetDigitValue``` (2认同)