C# Extension Method for String Data Type

10,506

Solution 1

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.

Solution 2

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.

Solution 3

Please read this article about currency implementations:
https://docs.microsoft.com/en-us/globalization/locale/currency-formatting

Example:

Double myNumber = Double.Parse("$1,250.85", NumberStyles.Any);

PS. You trying parse floating point value to decimal type.

Solution 4

  public static double ToDecimal(this string value)
        {
            ... your parsing magic
        }
Share:
10,506
Jimbo
Author by

Jimbo

Updated on June 15, 2022

Comments

  • Jimbo
    Jimbo almost 2 years

    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();