convert a float to string in F#?

后端 未结 5 980
醉话见心
醉话见心 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:13
    > sprintf "%f";;
    val it : (float -> string) = <fun:it@8>
    
    0 讨论(0)
  • 2021-01-11 12:27

    Just to round out the answers:

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

    :)

    0 讨论(0)
  • 2021-01-11 12:28
    string;;
    val it : (obj -> string) = <fun:it@1>
    
    0 讨论(0)
  • 2021-01-11 12:31

    Use the 'string' function.

    string 6.3f
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题