Validate double number in current culture

1.1k views Asked by At

There is a way to validate a double number in the current culture? I have tried this:

var number ="10,10";
double value = double.Parse(number,
                    NumberStyles.Float, 
                    CultureInfo.CurrentCulture);

If I try this with "es-ES" (where decimal separator is ",") then the parsing works perfect, I got an double 10.10, but if I try with "en-US" (where decimal separator is ".") the parsing can't understand the decimal point, so just omit it, so I get a 1010 incorrect number.

There is a way for me to get an exception when I tried to convert a wrong number for the specified culture?

Edit: by "," I don't mean thousand separator, I mean the decimal separator for some cultures like es-ES

1

There are 1 answers

1
Joe On BEST ANSWER

On my machine the following throws a FormatException, as expected:

var number ="10,10";
double value = double.Parse(number,
NumberStyles.Float, 
CultureInfo.InvariantCulture);

I suspect you're using NumberStyles.AllowThousands. For example, the following will return 1010:

var number ="10,10";
double value = double.Parse(number,
NumberStyles.Float | NumberStyles.AllowThousands, 
CultureInfo.InvariantCulture);

UPDATE

in response to comment:

... but if I'm using en-US "10,10" becames "1010" instead of throwing an error

That's not what I'd expect; for example, the following will throw a FormatException:

var number ="10,10";
double value = double.Parse(number,
NumberStyles.Float, 
new CultureInfo("en-US"));