gigi
gigi

Reputation: 3936

How to validate decimals based on the decimal separator?

I want to validate numbers and I only know the decimal separator ( dot or comma )

Eg.1: n1=12.4 and n2=1,234.5 -> both are valid for '.' as decimal separator and both invalid for ',' as decimal separator.

Eg.2: n1=12,4 and n2=1.234,5 -> both are valid for ',' as decimal separator and both invalid for '.' as decimal separator.

What have I tried so far?

CultureInfo cultureInfo = CultureInfo.InvariantCulture.Clone() as CultureInfo;
cultureInfo.NumberFormat.NumberDecimalSeparator = myDecimalSeparator;

and use

decimal.Parse(stringValue, cultureInfo);
  1. Eg1 + '.' => both valid OK
  2. Eg1 + ',' => both throw exception OK
  3. Eg2 + ',' => n1 throws exception OK , n2 throws exception WRONG
  4. Eg2 + '.' => n1 is 124 WRONG , n2 throws exception OK

What do you recommend me to do?

Upvotes: 0

Views: 503

Answers (4)

ThoBa
ThoBa

Reputation: 515

I suppose your normal culture is using the ',' as group separator and '.' as decimal separator. So by creating a new culture from the invariant culture and then setting the decimal separator to '.' is like doing nothing. On the other hand the newly created culture is still using ',' as a group separator, so by setting the decimal separator to ',' you are telling that ',' is both the group- and the decimal separator. This is why it works fine test 1 and 2 and it fails in the other tests.

Upvotes: 0

bash.d
bash.d

Reputation: 13207

Try to use

decimal.Parse(stringValue, cultureInfo.NumberFormat);

Only using the culture is insufficient. Look at MSDN.

Upvotes: 0

D Stanley
D Stanley

Reputation: 152521

You might try setting the group separator as well - meaning if you know the decimal separator is a comma set the group separator to a period:

CultureInfo cultureInfo = CultureInfo.InvariantCulture.Clone() as CultureInfo;
cultureInfo.NumberFormat.NumberDecimalSeparator = myDecimalSeparator;
cultureInfo.NumberFormat.NumberGroupSeparator = myGroupSeparator;

Upvotes: 2

polkduran
polkduran

Reputation: 2551

you can use decimal.TryParse instead to try to catch an exception

Upvotes: 0

Related Questions