convert a float to string in F#?

后端 未结 5 1007
醉话见心
醉话见心 2021-01-11 11:45

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

float -> string

5条回答
  •  甜味超标
    2021-01-11 12:40

    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.

提交回复
热议问题