sianabanana
sianabanana

Reputation: 920

C# Decimal.Parse comma problems

I need to parse a string to a decimal and it might be used in the UK or a european culture.

If in a european culture 2,00 would be 2

However, 2,00 would be invalid in the UK culture as a comma denotes a thousand.

If i use

Double.Parse("20,50", new CultureInfo("en-GB")) 

it returns 2050

I would have expected this to throw an invalid exception.

Can anyone help?

Upvotes: 3

Views: 4312

Answers (3)

pabdulin
pabdulin

Reputation: 35255

From the updated question, I can tell that UK culture posiibly uses , character as a possible places separation character, like 2,000 standing for 2000, and 2,000,000 for 2000000. But it can also be like 2,0,0,0 and it still be 2000.

From that point of view there are 3 possible scenarios:

  1. you are always recieving data in a local format, then there is no problem, you just parse string as it is (however there is one gotcha - user can change string formatting options, so you better crate new default local culture).
  2. you are recieving data in predefined format, then you use some fixed culture to parse string.
  3. you are recieving data in unknown format relatively to local, i.e. you can receive both local and non-local culture formats. This is the worst case, and there is no generic solution to this. I suggest reducing this to case 2 or 1, depending this task is easier.

Upvotes: 0

sianabanana
sianabanana

Reputation: 920

The point is that "2,00" in GB culutre should be invalid but it parses it like it was using a european culture.

I want it to throw an exception.

In contrast - Double.Parse("20.50", new CultureInfo("fr-FR")) throws an exception as the decimal place is invalid.

So why isnt this true for Double.Parse("20,50", new CultureInfo("en-GB"))

Upvotes: 1

Oded
Oded

Reputation: 499352

You should not be getting an exception, as , is a valid character in the parse string (as you said, it is interpreted as the thousands separator).

However, I am seeing 2050 for the same piece of code, not 20.50.

I would expect to see your result for the en-GB culture only if those have been manually changed in the control panel for that region (so if someone set the decimal separator to , and the thousands separator to something that is not ,).

Upvotes: 3

Related Questions