0

For a project I need to validate a currency. The requirements are that :

12 is valid 12.1 is valid 12.12 is also valid 12.123 is not valid.

Now I can use a regex to validate this like this one [RegularExpression(@"^(?!0\.00)\d{1,3}(.\d{3})*(\,\d\d)?$", ErrorMessage = "Must be a currency with no more then 2 digits after the." )]

but on tests it failing when someone uses another system. So in the Netherlands we use 12,00 and that validates but in the US and the UK they use 12.00 and that does not validate

I can also use a validation like this :

float num;
bool isValid = float.TryParse(str, NumberStyles.Currency,CultureInfo.GetCultureInfo("en-US"), // cached

out num);

but then I could not test if the num has only 2 numbers behind the .

I could set a culture but then its wierd for example to enter amounts like 2.45 where they are used to 2,45

Someone a idea how to make the validation work.

Regards,

Roelof

Roelof Wobben
  • 321
  • 1
  • 2
  • 8

1 Answers1

1

You can parse currency this way:

decimal currency = decimal.Parse("123.456", NumberStyles.Currency, CultureInfo.GetCultureInfo("en-US"));

If you don't want to accept three positions after dot you have two ways:

If you need float you can cast the decimal result.

fdafadf
  • 809
  • 5
  • 13