Ramy
Ramy

Reputation: 21261

convert a float to string in F#?

How do I convert a float to a string in F#. I'm looking for a function with this signature:

float -> string

Upvotes: 14

Views: 11846

Answers (5)

Tomas Petricek
Tomas Petricek

Reputation: 243041

As others pointed out, there are a few options. The two simplest are calling ToString method and using string function. There is a subtle difference between the two that you should be aware of. Here is what they do on my system:

> sprintf "%f" 1.2;;
val it : string = "1.200000"
> string 1.2;;
val it : string = "1.2"
> 1.2.ToString();;
val it : string = "1,2"

The first two are different, but both make sense, but why the heck did the last one return "1,2"?

That's because I have Czech regional settings where decimal point is written as comma (doh!) So, the string function uses invariant culture while ToString uses current culture (of a thread). In some weird cultures (like Czech :-)) this can cause troubles! You can also specify this explicitly with the ToString method:

> 1.2.ToString(System.Globalization.CultureInfo.InvariantCulture);;
val it : string = "1.2"

So, the choice of the method will probably depend on how you want to use the string - for presentation, you should respect the OS setting, but for generating portable files, you probably want invariant culture.

Upvotes: 24

Brian
Brian

Reputation: 118865

Just to round out the answers:

(fun (x:float) -> x.ToString())

:)

Upvotes: 2

Joel Mueller
Joel Mueller

Reputation: 28735

Use the 'string' function.

string 6.3f

Upvotes: 9

gradbot
gradbot

Reputation: 13862

string;;
val it : (obj -> string) = <fun:it@1>

Upvotes: 3

Jimmy
Jimmy

Reputation: 91452

> sprintf "%f";;
val it : (float -> string) = <fun:it@8>

Upvotes: 14

Related Questions