Decimal. Parse string, postfixed by a minus sign

后端 未结 4 917
栀梦
栀梦 2021-01-17 12:01
decimal decimalVal;
Decimal.TryParse(\"123-\", out decimalVal);
Console.WriteLine(decimalVal); // -123

Why do \"123-\" string parsed this way?

4条回答
  •  伪装坚强ぢ
    2021-01-17 12:23

    The NumberNegativePattern is only used for string output, but ignored when parsing. For parsing, another parameter is used: NumberStyles.

    Convert.ChangeType routes to decimal.Parse in your example, so if you directly used the correct overload, you can specify to not allow a trailing sign:

    var result = decimal.Parse("123-", NumberStyles.Number & ~NumberStyles.AllowTrailingSign); // will throw an exception
    

提交回复
热议问题