Extract decimal from start of string

前端 未结 3 1691
旧巷少年郎
旧巷少年郎 2020-12-06 06:59

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#

3条回答
  •  长情又很酷
    2020-12-06 07:12

    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.

提交回复
热议问题