Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

F# converting a string to a float

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
like image 342
moebius Avatar asked Apr 10 '11 19:04

moebius


2 Answers

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

like image 62
Tomas Petricek Avatar answered Sep 20 '22 12:09

Tomas Petricek


let myFloat = float searchString

Simple as that.

like image 28
Ramon Snir Avatar answered Sep 20 '22 12:09

Ramon Snir