Best way to parse float?

后端 未结 10 1054
无人及你
无人及你 2020-12-02 22:52

What is the best way to parse a float in CSharp? I know about TryParse, but what I\'m particularly wondering about is dots, commas etc.

I\'m having problems with my

相关标签:
10条回答
  • 2020-12-02 23:09

    Use a neutral culture (or one you know) when parsing with Try/Parse.

    0 讨论(0)
  • 2020-12-02 23:17

    If you want persist values ( numbers, date, time, etc... ) for internal purpose. Everytime use "InvariantCulture" for formating & parsing values. "InvariantCulture" is same on every computer, every OS with any user's culture/language/etc...

    string strFloat = (15.789f).ToString(System.Globalization.CultureInfo.InvariantInfo);
    float numFloat  = float.Parse(System.Globalization.CultureInfo.InvariantInfo, strFloat);
    string strNow   = DateTime.Now.ToString(System.Globalization.CultureInfo.InvariantInfo);
    DateTime now    = DateTime.Parse(System.Globalization.CultureInfo.InvariantInfo, strNow);
    
    0 讨论(0)
  • 2020-12-02 23:17

    Try to avoid float.Parse, use TryParse instead as it performs a lot better but does the same job. this also applies to double, DateTime, etc...

    (some types also offer TryParseExact which also performs even better!)

    0 讨论(0)
  • 2020-12-02 23:17

    you can know current Cuklture of your server with a simple statement:

    System.Globalization.CultureInfo culture = System.Globalization.CultureInfo.CurrentCulture;
    

    Note that there id a CurrentUICulture property, but UICulture is used from ResourceMeanager form multilanguages applications. for number formatting, you must considere CurrentCulture.

    I hope this will help you

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