F# converting a string to a float
Solution 1
There was a related question on conversion in the other way. It is a bit tricky, because the floating point format depends on the current OS culture. The float
function works on numbers in the invariant culture format (something like "3.14"). If you have float in the culture-dependent format (e.g. "3,14" in some countries), then you'll need to use Single.Parse
.
For example, on my machine (with Czech culture settings, which uses "3,14"):
> float "1.1";;
val it : float = 1.1
> System.Single.Parse("1,1");;
val it : float32 = 1.10000002f
Both functions throw exception if called the other way round. The Parse
method also has an overload that takes CultureInfo
where you can specify the culture explicitly
Solution 2
let myFloat = float searchString
Simple as that.
Solution 3
A side-effect-free
parseFloat function would look like:
let parseFloat s =
match System.Double.TryParse(s) with
| true, n -> Some n
| _ -> None
or even shorter:
let parseFloat s = try Some (float s) with | _ -> None
Related videos on Youtube
moebius
Updated on August 29, 2020Comments
-
moebius about 3 years
I have a simple problem that I haven't been able to figure out. I have a program that's supposed to read a float from input. Problem is it will come as string and I can't for the life of me figure out how to convert it to a float (yes I'm a complete newb).
let searchString = args.[0] let myFloat = hmm hmmm hmmmm
-
James Moore over 10 yearsSee @Thomas. Float string representation depends on the culture.
-
fahadash over 9 yearswhat happens when it fails to parse ?
-
Ramon Snir over 9 years@fahadash
System.FormatException
is thrown. -
Nestor Demeure over 5 yearsNote that
Single
is a float32, to get a float you need to useDouble.Parse
or its safer cousinDouble.TryParse
.