Click here to Skip to main content
15,895,011 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi Friends,
How to extract decimal values from a string
My string format is given below
C#
string message = "Validated AMT_RETENT in TBILL_DETAIL Table: [E]64.45 - [A]64.46";


I need a function which return two values similar to these
C#
public static ArrayList GetTwoNumbers(string message)
       {
          ArrayList ar = new ArrayList();
          ar[0] =64.45;
          ar[1] = 64.46;
          return ar;
       }
Posted
Updated 13-Apr-15 1:57am
v3
Comments
Style-7 13-Apr-15 7:58am    
use regular expression ans delete all symbols except numbers and "-"
system.text.regularexpressions.regex.replace,
after use split function,
String.Split
and convert to double from string
Praveen Kumar Upadhyay 13-Apr-15 8:12am    
Can you mention the output here, what output you want.
jinesh sam 14-Apr-15 11:59am    
Thanks Praveen.. I got solution from Peter

1 solution

Use Regex.
The Regex pattern in this case is
\d+.\d+

which means one or more number of digits (\d+) separated by a dot. If you want to have fixed number of decimal, say 2, then add {2} to the last one like this:
\d+.\d+{2}

Try to adapt from the example:
C#
using System;
using System.Text.RegularExpressions;

public class Program
{
    public static void Main()
    {
        string str = "Validated AMT_RETENT in TBILL_DETAIL Table: [E]64.45 - [A]64.46";
        Match match = Regex.Match(str, @"\d+.\d+");
        while (match.Success)
        {
            Console.WriteLine(match.Value);
            match = match.NextMatch();
        }
    }
}

The outcome will be:
VB
64.45
64.46

Learn more:
1. The 30 Minute Regex Tutorial[^]
2. http://www.dotnetperls.com/regex-match[^]
 
Share this answer
 
v3
Comments
jinesh sam 13-Apr-15 8:36am    
Thanks.. Its works fine :) One more doubt. If suppose the value is integer debug point not entering the while loop.How should i change the regex expression to accept both integer and decimal.
Maciej Los 13-Apr-15 9:03am    
5ed!
Peter Leow 14-Apr-15 7:27am    
Thank you, Maciej.
BillWoodruff 13-Apr-15 9:26am    
+5 ... perfect !
johannesnestler 13-Apr-15 10:30am    
until decimal separator isn't a dot...

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900