Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
270 views
in Technique[技术] by (71.8m points)

c# - Extract decimal from start of string

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;
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...