Hi. I need reg exspression what make this "123.12312" -> "123.32", or "23.323" -> "23.32" in c#. It must be only 2 digits after point :)
+2
A:
Assuming you are parsing a string and it has at least 2 digits after the point:
/[0-9]+\.[0-9]{2}/
Full Decent
2010-05-07 16:18:47
A:
I know you are asking about a Regex, but this seems like a better fit for Double.TryParse followed by proper formatting.
driis
2010-05-07 16:24:27
A:
Is there a particular reason you need to use Regular Expressions? I would think it'd be better to do something like String.Format("{0:0.00}", double)
. You can find a list of some helpful formatting examples at http://www.csharp-examples.net/string-format-double/
Timothy
2010-05-07 16:31:10
It is good too. If My question was without worlds reg expression I would choose you answer.
Sergii
2010-05-07 16:36:13
But in my code I will use your variant :).
Sergii
2010-05-07 16:43:03
A:
I don't realy know how regex works in C# but this is my regex
([0-9]+)(?:\.([0-9]{1,2})|)[0-9]*
Group 1 will get the part before the point and group 2 (if exists) will give the part behind the point (2 digits long)
the code here will produce all the matches out of a string:
StringCollection resultList = new StringCollection();
try {
Regex regexObj = new Regex(@"([0-9]+)(?:\.([0-9]{1,2})|)[0-9]*", RegexOptions.Singleline);
Match matchResult = regexObj.Match(subjectString);
while (matchResult.Success) {
resultList.Add(matchResult.Value);
matchResult = matchResult.NextMatch();
}
} catch (ArgumentException ex) {
// Syntax error in the regular expression
}
Spidfire
2010-05-07 16:36:57