[ACCEPTED]-F# converting a string to a float-type-conversion

Accepted answer
Score: 18

There was a related question on conversion in the other way. It is 12 a bit tricky, because the floating point 11 format depends on the current OS culture. The 10 float function works on numbers in the invariant 9 culture format (something like "3.14"). If 8 you have float in the culture-dependent 7 format (e.g. "3,14" in some countries), then 6 you'll need to use Single.Parse.

For example, on my machine 5 (with Czech culture settings, which uses 4 "3,14"):

> float "1.1";;
val it : float = 1.1
> System.Single.Parse("1,1");;
val it : float32 = 1.10000002f

Both functions throw exception 3 if called the other way round. The Parse method 2 also has an overload that takes CultureInfo where you 1 can specify the culture explicitly

Score: 9

let myFloat = float searchString

Simple as that.

0

Score: 6

A side-effect-free parseFloat function would look like:

let parseFloat s =
    match System.Double.TryParse(s) with 
    | true, n -> Some n
    | _ -> None

or 1 even shorter:

let parseFloat s = try Some (float s) with | _ -> None

More Related questions