The string value is "90-"
. Why does the decimal parse it as "-90"
but double
throws a FormatException
?
var inputValue= "90-";
Console.WriteLine(decimal.Parse(inputValue));
Console.WriteLine(double.Parse(inputValue));
Parse(String, IFormatProvider) Converts the string representation of a number to its Decimal equivalent using the specified culture-specific format information. Parse(String, NumberStyles) Converts the string representation of a number in a specified style to its Decimal equivalent.
Syntax: public static int ToInt32 (decimal value); Here, the value is the decimal number which is to be converted. Return Value: It returns a 32-bit signed integer equivalent to the specified value. Exception: This method will give OverflowException if the specified value is less than MinValue or greater than MaxValue.
The decimal.Parse(string s)
overload, by default, is called with NumberStyle NumberStyles.Number
which is defined as:
Indicates that the AllowLeadingWhite, AllowTrailingWhite, AllowLeadingSign, AllowTrailingSign, AllowDecimalPoint, and AllowThousands styles are used. This is a composite number style.
Note that AllowTrailingSign
is included. If you wish to customize the behaviour then you should explicitly call the overload that allows you to specify a number style and tailor it to your needs.
The implementation is different between the two:
public static double Parse(String s) {
return Parse(s, NumberStyles.Float| NumberStyles.AllowThousands, NumberFormatInfo.CurrentInfo);
}
public static Decimal Parse(String s) {
return Number.ParseDecimal(s, NumberStyles.Number, NumberFormatInfo.CurrentInfo);
}
where
NumberStyles.Float = AllowLeadingWhite | AllowTrailingWhite | AllowLeadingSign |
AllowDecimalPoint | AllowExponent,
NumberStyles.Number = AllowLeadingWhite | AllowTrailingWhite | AllowLeadingSign | AllowTrailingSign |
AllowDecimalPoint | AllowThousands
So decimal.Parse
allows trailing signs but double.Parse
does not.
Looks like the documentation on MSDN is inaccurate:
Parameter s contains a number of the form:
[ws][sign][digits,]digits[.fractional-digits][ws]
It should indicate that a trailing sign is valid as well.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With