Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to detect if string is currency in c#

Usually when I have need to convert currency string (like 1200,55 zł or $1,249) to decimal value I do it like this:

if (currencyString.Contains("zł)) {
    decimal value = Decimal.Parse(dataToCheck.Trim(), NumberStyles.Number | NumberStyles.AllowCurrencySymbol);
}

Is there a way to check if string is currency without checking for specific currency?

like image 235
MadBoy Avatar asked Aug 27 '11 12:08

MadBoy


2 Answers

If you just do the conversion (you should add | NumberStyles.AllowThousands | NumberStyles.AllowDecimalPoint as well) then if the string contains the wrong currency symbol for the current UI the parse will fail - in this case by raising an exception. It it contains no currency symbol the parse will still work.

You can therefore use TryParse to allow for this and test for failure.

If your input can be any currency you can use this version of TryParse that takes a IFormatProvider as argument with which you can specify the culture-specific parsing information about the string. So if the parse fails for the default UI culture you can loop round each of your supported cultures trying again. When you find the one that works you've got both your number and the type of currency it is (Zloty, US Dollar, Euro, Rouble etc.)

like image 195
ChrisF Avatar answered Sep 26 '22 21:09

ChrisF


As I understand it's better to do:

decimal value = -1;
if (Decimal.TryParse(dataToCheck.Trim(), NumberStyles.Number | 
  NumberStyles.AllowCurrencySymbol,currentCulture, out value)
   {do something}

See Jeff Atwood description about TryParse. It doesn't throw an exception and extremely faster than Parse in exception cases.

like image 38
Saeed Amiri Avatar answered Sep 25 '22 21:09

Saeed Amiri