Why decimal.Parse(10 10) is valid?
Why decimal.Parse(10开发者_JAVA百科 10)
is valid?
decimal c;
try
{
c = decimal.Parse("10 10");
Console.Write(c);
Console.ReadLine();
}
catch (Exception)
{
throw;
}
This throws an exception when I run it - which leads me to suspect that it's culture-sensitive.
My guess is that you're in a culture which uses space as a "thousands" separator. For example, if I try to parse "10,10" that works because comma is the thousands separator in my default culture.
To prevent this, use
decimal value = decimal.Parse(text, NumberStyles.None);
... or some other appropriate combination of NumberStyles
which excludes AllowThousands
.
From MSDN: "Parameter s is interpreted using the NumberStyles.Number style. This means that white space and thousands separators are allowed but currency symbols are not. To explicitly define the elements (such as currency symbols, thousands separators, and white space) that can be present in s, use either the Decimal.Parse(String, NumberStyles) or the Decimal.Parse(String, NumberStyles, IFormatProvider) method."
http://msdn.microsoft.com/en-us/library/cafs243z.aspx
edit: To further clarify, you need to either
- explicitly set the culture of your application to one which does NOT allow whitespace in numbers, or
- explicitly provide a NumberStyles parameter which specifies that whitespace is NOT allowed
edit 2: Jon Skeet's answer is correct. For example, the following does NOT throw an exception, because whitespace is used as thousands separators in sv-SE:
Decimal.Parse(" 10 10 ", CultureInfo.GetCultureInfo("sv-SE").NumberFormat)
The following, however, DOES throw an exception:
Decimal.Parse(" 10 10 ", CultureInfo.GetCultureInfo("en-US").NumberFormat)
I just ran this code on Visual Studio 2010/C# 4.0, and got a FormatException, as expected. What regional settings is your computer configured to use? Is it possible that you have " " (space) as a thousands separator or decimal separator?
精彩评论