Search code examples
c#stringextension-methodsnumbers

C# Extension Method for String Data Type


My web application deals with strings that need to be converted to numbers a lot - users often put commas, units (like cm, m, g, kg) and currency symbols in these fields so what I want to do is create a string extension method that cleans the field up and converts it to a decimal.

For example:

decimal myNumber = "15 cm".ToDecimal();

Solution

  • Are you expecting users of different 'cultures' to use your application? If so it's better to factor in the user's regional settings:

    static decimal ToDecimal(this string str)
    {
        return Decimal.Parse(str, CultureInfo.CurrentCulture);
    }
    

    Or you could replace every character in str that isn't a digit or the CultureInfo.CurrentCulture.NumberFormat.CurrencyDecimalSeparator value and then parse it as a decimal.

    EDIT:
    It is generally accepted that extension methods should have their own namespace. This will avoid naming conflicts and force the end user to selectively import the extensions they need.