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?
If you just do the conversion (you should add
| NumberStyles.AllowThousandsas 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.| NumberStyles.AllowDecimalPoint
You can therefore use
TryParseto allow for this and test for failure.If your input can be any currency you can use this version of
TryParsethat takes aIFormatProvideras 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.)