提取字符串十进制 [英] Extract decimal from string

查看:116
本文介绍了提取字符串十进制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一样的字符串5.5千克7.90克,我想获得 5.5 7.90 作为十进制值。我怎样才能得到这样的结果 C#还有一件事,我的字符串总是以小数。

我的code是在这里。但它会给时,它会遇到任何事情,除了十进制错误。

 柱重量=的AttributeValue;
如果(!string.IsNullOrEmpty(重量))
{
    product.Weight = Convert.ToDecimal(的AttributeValue);
}
其他
{
    product.Weight =0.00米;
}
 

解决方案

我想创建一个普通的前pression相匹配的领先的数字部分。这将部分取决于你是否总是的有一个小数点,您是否允许逗号为千位分隔符,是否会一直使用作为小数点等,这可能是这个样子,但:

  ^  -  \ D +?(:\ \ D +?)?
 

然后匹配文本,经常EX pression,把比赛的价值(如果成功),并使用 decimal.Parse double.Parse 该值:

 正则表达式的regex ​​=新的正则表达式(@^  -  \ D +(?:?。?\ \ D +));
比赛比赛= regex.Match(文本);
如果(match.Success)
{
    体重= decimal.Parse(match.Value,CultureInfo.InvariantCulture);
}
 

请注意,对于自然的价值观,如质量,您的可以的是更好地与十进制。后者更适合于人工的​​价值观,如货币,这是自然pssed十进制最好的EX $ P $,并有精确值。这取决于你在做什么,但。

I am having a string like 5.5kg or 7.90gram and I want to get 5.5 or 7.90 as a decimal value. How can I get such result in c# and one more thing that my string will always starts with decimal.

My Code is here. But it will give error whenever it will encounter any thing except decimal.

string weight = attributeValue;
if (!string.IsNullOrEmpty(weight))
{
    product.Weight = Convert.ToDecimal(attributeValue);
}
else
{
    product.Weight = 0.00m;
}

解决方案

I would create a regular expression matching the leading number part. This will partly depend on whether you will always have a decimal point, whether you want to allow commas for thousands separators, whether it will always use . as the decimal point, etc. It might look something like this though:

^-?\d+(?:\.\d+)?

Then match that regular expression against your text, take the value of the match (if it's successful) and use decimal.Parse or double.Parse on that value:

Regex regex = new Regex(@"^-?\d+(?:\.\d+)?");
Match match = regex.Match(text);
if (match.Success)
{
    weight = decimal.Parse(match.Value, CultureInfo.InvariantCulture);
}

Note that for "natural" values such as mass, you may be better off with double than decimal. The latter is more appropriate for "artificial" values such as currency, which are naturally best expressed in decimal and have exact values. It depends on what you're doing though.

这篇关于提取字符串十进制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆