Why does NumberStyles.AllowThousands work for int.Parse but not for double.Parse in this example?

前端 未结 1 1153
不知归路
不知归路 2021-01-18 07:44

To parse a string representing a number, with a comma separating thousand digits from the rest, I tried

int tmp1 = int.Parse("1,234", NumberStyles.A         


        
相关标签:
1条回答
  • 2021-01-18 08:03

    You should pass AllowDecimalPoint, Float, or Number style (latter two styles are just a combination of several number styles which include AllowDecimalPoint flag):

    double.Parse("1,000.01", NumberStyles.AllowThousands | NumberStyles.AllowDecimalPoint)
    

    When you provide some number style to parsing method, you specify exact style of elements which can present in the string. Styles which are not included considered as not allowed. Default combination of flags (when you don't specify style explicitly) for parsing double value is NumberStyles.Float and NumberStyles.AllowThousands flags.

    Consider your first example with parsing integer - you haven't passed AllowLeadingSign flag. Thus the following code will throw an exception:

    int.Parse("-1,234", NumberStyles.AllowThousands)
    

    For such numbers, AllowLeadingSign flag should be added:

    int.Parse("-1,234", NumberStyles.AllowThousands | NumberStyles.AllowLeadingSign)
    
    0 讨论(0)
提交回复
热议问题