简体   繁体   English

更优雅的方式做F#中的CultureInvariant Double.parse

[英]More elegant way to do CultureInvariant Double.parse in F#

I have an array of numbers in string format (eg [|"1"; "2"; "3" ...|]) and want to convert them to doubles, however I want to do it in CultureInvariant way. 我有一个字符串格式的数字数组(例如[|“1”;“2”;“3”... |])并希望将它们转换为双精度数,但我想以CultureInvariant的方式进行。 Of course I could do: 我当然可以这样做:

[|"1"; "2"|] |> Array.map (fun (a) -> Double.Parse(a, CultureInfo.InvariantCulture))

However, is there any way to do it like this: 但是,有没有办法这样做:

[|"1"; "2"|] |> Array.map Double.Parse

, but with CultureInfo.InvariantCulture? ,但是使用CultureInfo.InvariantCulture? This code will look much more readable. 此代码看起来更具可读性。 In another words, are there any ways to pass CultureInfo.InvariantCulture to Double.parse in flow, or set CultureInfo.InvariantCulture globally for all program/script. 换句话说,有没有办法将CultureInfo.InvariantCulture传递给flow中的Double.parse,或者为所有程序/脚本全局设置CultureInfo.InvariantCulture。

In F# double and float are the same thing, and they both correspond to a C# double . 在F#中, doublefloat是相同的,它们都对应于C# double See this answer . 看到这个答案

Therefore you can simply use the float operator for this, which handles conversions from many types including strings: 因此,您可以简单地使用float运算符来处理来自多种类型(包括字符串)的转换:

[|"1"; "2"|] |> Array.map float

The F# conversion operators all sensibly use CultureInfo.InvariantCulture without the need for you to specify it: See this function from the F# source code used by the float operator. F#转换运算符都明智地使用CultureInfo.InvariantCulture而无需您指定它:从float运算符使用的F#源代码中查看此函数

If you want to use C# compatible terminology you can use the double operator, which is just an alias for float . 如果要使用C#兼容术语,可以使用double运算符,它只是float的别名。

If you need a 32-bit float (the C# float), you can use float32 . 如果需要32位浮点数(C#float),可以使用float32

Pretty straightforward to define a helper function and use that: 非常简单地定义辅助函数并使用它:

let ParseInvariant a = Double.Parse(a, CultureInfo.InvariantCulture)
let b = [|"1"; "2"|] |> Array.map ParseInvariant

or define an extension method: 或定义扩展方法:

type Double with
    static member ParseInvariant a = Double.Parse(a, CultureInfo.InvariantCulture)
let b = [|"1"; "2"|] |> Array.map Double.ParseInvariant

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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