开发者

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


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.


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


Use the 'string' function.

string 6.3f


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


Just to round out the answers:

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

:)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜