F# converting a string to a float

11,413

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
Share:
11,413

Related videos on Youtube

moebius
Author by

moebius

Updated on August 29, 2020

Comments

  • moebius
    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
    James Moore over 10 years
    See @Thomas. Float string representation depends on the culture.
  • fahadash
    fahadash over 9 years
    what happens when it fails to parse ?
  • Ramon Snir
    Ramon Snir over 9 years
    @fahadash System.FormatException is thrown.
  • Nestor Demeure
    Nestor Demeure over 5 years
    Note that Single is a float32, to get a float you need to use Double.Parse or its safer cousin Double.TryParse.

Related