Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
like image 719
Jimbo Avatar asked Sep 02 '26 13:09

Jimbo


2 Answers

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.

like image 88
Phil Gan Avatar answered Sep 04 '26 02:09

Phil Gan


An extension method is of the following form:

public static class StringExtensions
{
    public static decimal ToDecimal(this string input)
    {
        //your conversion code here
    }
}
  • The containing class must be static. The method is also static Note the "this" keyword. I recommend the convention of grouping extension methods by the type to which they refer, but there is no requirement to do so.

Here is a guide for writing extension methods.

like image 35
dpurrington Avatar answered Sep 04 '26 03:09

dpurrington