开发者

Why decimal.Parse(10 10) is valid?

开发者 https://www.devze.com 2023-04-05 21:28 出处:网络
Why decimal.Parse(10开发者_JAVA百科 10) is valid? I need to get exception in such case. Please advise me something.

Why decimal.Parse(10开发者_JAVA百科 10) is valid?

I need to get exception in such case.

Please advise me something.

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

  1. explicitly set the culture of your application to one which does NOT allow whitespace in numbers, or
  2. 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?

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号