Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decimal Parse Issue

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));
like image 314
david Avatar asked Apr 25 '14 15:04

david


People also ask

What is decimal parse?

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.

How to take Decimal input in c#?

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.


2 Answers

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.

like image 96
J... Avatar answered Oct 19 '22 03:10

J...


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.

like image 23
D Stanley Avatar answered Oct 19 '22 02:10

D Stanley