moebius
moebius

Reputation: 213

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

Upvotes: 16

Views: 13106

Answers (3)

Alan R. Soares
Alan R. Soares

Reputation: 1784

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

Upvotes: 7

Tomas Petricek
Tomas Petricek

Reputation: 243051

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

Upvotes: 19

Ramon Snir
Ramon Snir

Reputation: 7560

let myFloat = float searchString

Simple as that.

Upvotes: 9

Related Questions