Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

locale

f#

I have an array of numbers in string format (e.g. [|"1"; "2"; "3" ...|]) and want to convert them to doubles, however I want to do it in CultureInvariant way. 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? 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.

like image 948
Darkkey Avatar asked Jan 05 '23 17:01

Darkkey


1 Answers

In F# double and float are the same thing, and they both correspond to a C# double. See this answer.

Therefore you can simply use the float operator for this, which handles conversions from many types including strings:

[|"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.

If you want to use C# compatible terminology you can use the double operator, which is just an alias for float.

If you need a 32-bit float (the C# float), you can use float32.

like image 188
TheQuickBrownFox Avatar answered Jan 13 '23 01:01

TheQuickBrownFox