Reputation: 3936
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);
What do you recommend me to do?
Upvotes: 0
Views: 503
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
Reputation: 13207
Try to use
decimal.Parse(stringValue, cultureInfo.NumberFormat);
Only using the culture is insufficient. Look at MSDN.
Upvotes: 0
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
Reputation: 2551
you can use decimal.TryParse
instead to try to catch an exception
Upvotes: 0