decimal decimalVal;
Decimal.TryParse(\"123-\", out decimalVal);
Console.WriteLine(decimalVal); // -123
Why do \"123-\" string parsed this way?
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
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
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
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.