从字符串开头提取小数 [英] Extract decimal from start of string
问题描述
我有一个字符串,例如 5.5kg
或 7.90gram
,我想获取 5.5
或 7.90
作为十进制值。我如何在C#中得到这样的结果以及我的字符串始终以十进制开头的另一件事。
I have 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.
这是我的代码,只要遇到除小数点以外的其他内容,都会抛出错误。
Here is my code that throws an error whenever it will encounter anything except a 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+)?
然后将正则表达式与您的文本进行匹配,取匹配的值(如果成功)并在该值上使用 decimal.Parse
或 double.Parse
:
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);
}
请注意,对于自然值,例如质量,您可能会与十进制
相比,使用 double
更好。后者更适用于人工值,例如货币,自然最好用十进制表示并具有精确值。这取决于您在做什么。
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屋!