This article introduces a regular small instance, which is extracted using the C # syntax to match the numbers in the string. and introduce the "rounding" in C # numeric calculations. C # Regular matching numbers
This is the instance code that extracts the number (including decimals) in the string :
String str = "Discount 60,000";
/** \\d+\\.? \\d*
* \d indicates
the number * + indicates that the preceding number has one or more (at least one occurrence)
* \. Here is the point to note that. Represents any atom, which is escaped here to represent a simple decimal place
*? represents 0 or 1
* * means 0 times or more Times
/Regex r = new Regex ("\\d+\\.") \\d* ");
BOOL IsMatch = R.ismatch (str);
MatchCollection MC = r.matches (str);
string result = String. Empty;
for (int i = 0; I < MC. Count; i++)
{
results = mc[i];//Match result is a complete number, this can not do the concatenation of the
}
Console.WriteLine (outcome);
Note that translating the decimal point is easy to ignore
C # "Rounding" Calculation processing
C # preserves a decimal, rounded
result = "3.55";
Use the Math.Round method
Decimal d = math.round (Convert.todecimal (Result), 1, Midpointrounding.awayfromzero);
Console.WriteLine (D.tostring ());
C # Extracts the number from the string, and after rounding, replaces the original number
String str = "Discount 59,950";
Regex r = new Regex ("\\d+\\.") \\d* ");
string result = String. Empty;
if (R.ismatch (str))
{
MatchCollection mc = r.matches (str);
String temp = mc. Count > 0? Mc[0]. ToString (): "";
String show = Math.Round (Convert.todecimal (temp), 1, Midpointrounding.awayfromzero). ToString ();
Console.WriteLine (show);
result = Regex.Replace (str, "\\d+\\.") \\d* ", show);
}
else
{result
= str;
}
Console.WriteLine (result);