[C #] Simple and fast to convert various numeric words to numbers (String to int)

I believe that when you are writing programs, you must have a lot of opportunities to convert numeric strings into int or float type values, but the numeric characters may not be very clean, sometimes there are thousands Quantile, currency symbol, blanks before and after, or even not decimal, so the conversion is a bit tiring, like thousandths or currency symbols, I used Replace to delete symbols such as $ and then convert them, but if you use them. Net Framework 2.0 and above are actually not so troublesome, there are built-in functions to help you deal with these miscellaneous things, let us see how to do it.

I believe that when you are writing programs, you must have a lot of opportunities to convert numeric strings into int or float type values, but the numeric characters may not be very clean, sometimes There will be thousands, currency symbols, blanks before and after, or even not decimal, so the conversion is a bit tiring, like the thousands or currency symbols, I used Replace to delete symbols such as $ and then convert them, but if If you are using .Net Framework 2.0 or above, it doesn’t have to be so troublesome. There are built-in functions to help you deal with these miscellaneous things. Let’s see how to do it.

Use int.Parse or int.TryParse

If you read it right, it is int.Parse. You can use int.Parse to contain thousands, String transformation of currency symbol.

Maybe you will say that I lied to you, then you must have not looked at the other parameters of the Parse method (Method), Parse has a parameter System.Globalization.NumberStyles enumeration type (Enum) is used to declare the allowed style of the incoming string, and the members of NumberStyles are as follows:

< tr>

Name Description
None It must be exactly a decimal integer number.
AllowLeadingWhite Allow white space before the number.
AllowTrailingWhite Allow white space after the number.
AllowLeadingSign Allow signs in front of numbers .
AllowTrailingSign Allow sign behind the number .
AllowParentheses Allows a pair of brackets to enclose numbers , The brackets indicate that the string to be parsed represents a negative number.
AllowDecimalPoint Numerical strings can have decimal points.
AllowThousands The numeric string can contain group separation symbol.
AllowExponent Numerical strings can use exponential notation .
AllowCurrencySymbol The numeric string can contain currency symbols.
AllowHexSpecifier Use hexadecimal for numeric strings Value, but cannot add “0x” or “&h” in front of it.

The following are the combination members:

< tr>

Name Description
Integer AllowLeadingWhite | AllowTrailingWhite | AllowLeadingSign.
HexNumber AllowLeadingWhite | AllowTrailingWhite | AllowHexSpecifier.
Number AllowLeadingWhite | AllowTrailingWhite | AllowLeadingSign | AllowTrailingSign | AllowDecimalPoint | AllowThousands.
Float AllowLeadingWhite | AllowTrailingWhite | AllowLeadingSign | AllowDecimalPoint | AllowExponent.
Currency All except AllowExponent and AllowHexSpecifier model.
Any All modes except AllowHexSpecifier.

This is only a brief table. For details, please see [MSDN] NumberStyles enumeration type.

The default NumberStyles used by int.Parse is Integer. Integer only allows blank and addition and subtraction modes, so pass in others.

There are other numeric ValueTypes such as decimal.Parse, float.Parse, byte.Parse, short.Parse, etc., which support the use of NumberStyles, because in fact they are all used The same Class handles the conversion, but the NumberStyles used are different. For example, decimal.Parse uses NumberStyles.Currency by default.

TryParse is a better method for conversion, because Parse is that the format of the value is incorrect and an Exception will be thrown. If the program is not written well, the program may be closed, but TryParse is different. Incorrect format only does not return the converted value, it will not cause disaster for the big too (but not necessarily, because the variable that used TryParse to receive the converted value in the original case must have a value, but the conversion failed and nothing else was done. In the end, NullReferenceException may still be generated. To avoid such problems, you can refer to the spirit of defensive programming (Defensive programming).

Usage example

//Contains thousandths

int value1 = int.Parse("1,000,000", NumberStyles.AllowThousands);
int value2 = (int)decimal.Parse("1,000,000"); //Of course, decimal.Parse can also be used, just to transform

//But if you have decimals, you can’t use int. Parse will fail
int value3 = (int)decimal.Parse("1,000,000.50", NumberStyles.AllowThousands | NumberStyles.AllowDecimalPoint);

//A currency symbol is also ok, but the $ and the number cannot be separated, but the computer’s cultural setting is used
int value4 = int.Parse("NT$1,000,000", NumberStyles.AllowCurrencySymbol | NumberStyles.AllowThousands);

//You can also use the cultural settings of different countries
int value5 = int.Parse("$1,000,000", NumberStyles.Any, CultureInfo.GetCultureInfo("en")); //United States
int value6 = int.Parse("¥1,000,000", NumberStyles.Any, CultureInfo.GetCultureInfo("ja")); //Japan

//Index
int value7 = int.Parse("1E+6", NumberStyles.AllowExponent);

//parentheses
int value8 = int.Parse("(1,000,000)", NumberStyles.AllowParentheses | NumberStyles.AllowThousands);

/hexadecimal
int value9 = int.Parse("F4240",NumberStyles.HexNumber);

//Blank before and after
int value10 = int.Parse(" 1000000 ",NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite);

//But the percentage value is not supported, additional processing is required
int str = "10.5%";
if (str.IndexOf(‘%‘)>-1)
{
int value11 = decimal.Parse(str.TrimEnd(new char[] {‘%‘,‘ ‘})) / 100M;
}

//2 or octal, use another Method
int value12 = Convert.ToInt32("11110100001001000000", 2);
int value13 = Convert.ToInt32("3641100", 8);

//If you are lazy, you can write like this, but the performance will be a little bit worse
int value14 = (int)decimal.Parse("1,000,000", NumberStyles.Any);

Reference data

[MSDN]NumberStyles enumeration type

[Wikipedia]Defensive programming

Original: Large column [C#] Convert various numerical characters into numbers (string to int) simply and quickly

WordPress database error: [Table 'yf99682.wp_s6mz6tyggq_comments' doesn't exist]
SELECT SQL_CALC_FOUND_ROWS wp_s6mz6tyggq_comments.comment_ID FROM wp_s6mz6tyggq_comments WHERE ( comment_approved = '1' ) AND comment_post_ID = 3094 ORDER BY wp_s6mz6tyggq_comments.comment_date_gmt ASC, wp_s6mz6tyggq_comments.comment_ID ASC

Leave a Comment

Your email address will not be published.