问题描述
我的 Web 应用程序处理需要大量转换为数字的字符串 - 用户经常在这些字段中放置逗号、单位(如 cm、m、g、kg)和货币符号,所以我想做的是创建一个清除字段并将其转换为小数的字符串扩展方法.
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.
例如:
decimal myNumber = "15 cm".ToDecimal();
推荐答案
您是否希望不同文化"的用户使用您的应用程序?如果是这样,最好考虑用户的区域设置:
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);
}
或者您可以替换 str 中不是数字或 CultureInfo.CurrentCulture.NumberFormat.CurrencyDecimalSeparator
值的每个字符,然后将其解析为小数.
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.
人们普遍认为扩展方法应该有自己的命名空间.这将避免命名冲突并强制最终用户有选择地导入他们需要的扩展.
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.
这篇关于字符串数据类型的 C# 扩展方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!