C# Extension Method for String Data Type

后端 未结 7 1861
清酒与你
清酒与你 2020-12-11 10:58

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

相关标签:
7条回答
  • 2020-12-11 12:02

    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.

    0 讨论(0)
提交回复
热议问题