Decimal. Parse string, postfixed by a minus sign

后端 未结 4 918
栀梦
栀梦 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
    
    0 讨论(0)
  • 2021-01-17 12:34

    This is an accepted format for Decimal.Parse. The style option to the Parse method allows for leading and trailing signs.

    Read more: http://msdn.microsoft.com/en-us/library/91fwbcsb.aspx

    0 讨论(0)
  • 2021-01-17 12:44

    NumberStyles.Number enumerator is used by default:

    Indicates that the AllowLeadingWhite, AllowTrailingWhite, AllowLeadingSign, AllowTrailingSign, AllowDecimalPoint, and AllowThousands styles are used. This is a composite number style

    http://msdn.microsoft.com/en-us/library/system.globalization.numberstyles.aspx

    0 讨论(0)
  • 2021-01-17 12:45

    The Decimal.TryParse Method parses the input with NumberStyles.Number by default. NumberStyles.Number includes NumberStyles.AllowTrailingSign.

    Decimal.TryParse Method (String, Decimal)

    [...]
    Parameter s is interpreted using the NumberStyles.Number style.
    [...]

    Number   Indicates that the AllowLeadingWhite, AllowTrailingWhite, AllowLeadingSign, AllowTrailingSign, AllowDecimalPoint, and AllowThousands styles are used. This is a composite number style.

    AllowTrailingSign   Indicates that the numeric string can have a trailing sign. Valid trailing sign characters are determined by the NumberFormatInfo.PositiveSign and NumberFormatInfo.NegativeSign properties.

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