C # Regular Match (extract number from String) and C # "rounding"

Source: Internet
Author: User

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);

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.