10

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;
}
0

3 Answers 3

27

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.

3
  • The current regex will only match floats/integers at the start of the string due to ^ anchor. To extract numbers from any location in the string, use -?\d+(?:\.\d+)?. Or [-+]?[0-9]*\.?[0-9]+(?:[eE][-+]?[0-9]+)? Commented Nov 23, 2016 at 13:31
  • @WiktorStribiżew: Yup, because I answered the question that was asked: "one more thing that my string will always starts with decimal".
    – Jon Skeet
    Commented Nov 23, 2016 at 13:32
  • Yes, sure, just the title does not imply that, I think it should be edited. Commented Nov 23, 2016 at 13:34
2

here is a completely different approach

    string oldstr = "1.7meter";
        Char[] strarr = oldstr.ToCharArray().Where(c => Char.IsDigit(c) || Char.IsPunctuation(c)).ToArray();
        decimal number = Convert.ToDecimal( new string(strarr)); 
0

For your input format you can get decimal by this code

var weight =Decimal.Parse( Regex.Match(input_string, "[0-9]*\\.*[0-9]*").Value);

if your input string is in different format then you have to change the regex pattern.

Not the answer you're looking for? Browse other questions tagged or ask your own question.