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
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
let myFloat = float searchString
Simple as that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With