[C #] Various quick and easy word into digital values (string to int)

I believe everyone in the writing process, there must be a lot of opportunities you want the value of words (numeric string) converted to int or float type value, but the value of words may not be very clean, sometimes there are thousands separator, currency symbol, surrounding blanks, not even 10 decimal, so the conversion a bit tired, like the thousandth or currency symbol before I was to use Replace, and then delete the $ symbols such conversion, but if you are using .Net Framework 2.0 or more in fact not so much trouble, there are built-in features to help you deal with these clutter, let's look at how to do it.


I believe everyone in the writing process, there must be a lot of opportunities you want the value of words (numeric string) converted to int or float type value, but the value of words may not be very clean, sometimes there are thousands separator, currency symbol, surrounding blanks, not even 10 decimal, so the conversion a bit tired, like the thousandth or currency symbol before I was to use Replace, and then delete the $ symbols such conversion, but if you are using .Net Framework 2.0 or more in fact not so much trouble, there are built-in features to help you deal with these clutter, let's look at how to do it.

Use int.Parse or int.TryParse

Int.Parse is not wrong, it can be done using int.Parse String containing the thousandth, currency symbol of transformation.

You might say I lie to you, that surely did not look at other parameters Parse this method (Method) is, Parse which has a parameter System.Globalization.NumberStyles enumerated type (Enum) said in a statement that is used to sample the incoming string permissive, and members NumberStyles following table:

name Explanation
None You must be just right is a decimal integer numbers.
AllowLeadingWhite In front of numbers allowed blank.
AllowTrailingWhite Digital allows the rear blank.
AllowLeadingSign The front of the digital sign is allowed.
AllowTrailingSign Allow rearward digital sign.
AllowParentheses Allowing a pair of numbers enclosed in parentheses, brackets indicate string representing a negative number to be parsed.
AllowDecimalPoint Numeric string can have a decimal point.
AllowThousands The group may comprise numeric string delimiter.
AllowExponent Numeric string may be employed to exponential notation.
AllowCurrencySymbol Numeric string may include currency symbols.
AllowHexSpecifier Numeric string hexadecimal value, but can not add "0x" or "& h" in front.

The following is a combination of members:

name Explanation
Integer AllowLeadingWhite | AllowTrailingWhite | AllowLeadingSign.
HexNumber AllowLeadingWhite | AllowTrailingWhite | AllowHexSpecifier.
Number AllowLeadingWhite | AllowTrailingWhite | AllowLeadingSign | AllowTrailingSign | AllowDecimalPoint | AllowThousands.
Float AllowLeadingWhite | AllowTrailingWhite | AllowLeadingSign | AllowDecimalPoint | AllowExponent.
Currency In addition to all modes of AllowExponent and AllowHexSpecifier.
Any In addition to all modes of AllowHexSpecifier.

This is only the profile, details see [MSDN] NumberStyles enumerated type.

The NumberStyles int.Parse default is Integer, Integer only allowed to have a blank before and after the addition and subtraction mode, so the incoming other.

There are other such decimal.Parse, float.Parse, byte.Parse, short.Parse etc. numeric ValueType support the use of NumberStyles, because in fact they are handled with the same conversion only Class, just NumberStyles used is different, the default value NumberStyles.Currency decimal.Parse used.

The TryParse is a better method when converted because Parse is the format incorrect value will throw Exception if the program does not write may make the program closes, but TryParse not the same, the format is not only incorrect value return value after the conversion it will not cause too big of a disaster (though not necessarily, because that might otherwise encounter with TryParse of receiving variable conversion value there will be value, but the conversion failed and did not do the other, at last, may still produce a NullReferenceException, to avoid such problems, you can refer to the spirit of defensive programming (defensive programming) of).

Examples of use

//含有千分位
int value1 = int.Parse("1,000,000", NumberStyles.AllowThousands);		
int value2 = (int)decimal.Parse("1,000,000"); //当然用decimal.Parse也可以,只是要转型

//但有小数就不能用int.Parse会失败
int value3 = (int)decimal.Parse("1,000,000.50", NumberStyles.AllowThousands | NumberStyles.AllowDecimalPoint);	

//有货币符号也可以,但$与数字不能分开,但使用电脑的文化设定
int value4 = int.Parse("NT$1,000,000", NumberStyles.AllowCurrencySymbol | NumberStyles.AllowThousands);

//也可以使用不同国家的文化设定
int value5 = int.Parse("$1,000,000", NumberStyles.Any, CultureInfo.GetCultureInfo("en")); //美国	
int value6 = int.Parse("¥1,000,000", NumberStyles.Any, CultureInfo.GetCultureInfo("ja")); //日本

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

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

//16进制
int value9 = int.Parse("F4240",NumberStyles.HexNumber);

//前后空白
int value10 = int.Parse("  1000000  ",NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite);

//但百分值不支持,要额外处理
int str =  "10.5%";
if (str.IndexOf('%')>-1)
{
	int value11 = decimal.Parse(str.TrimEnd(new char[] {'%',' '})) / 100M;		
}

//2或8进制,要使用另一个 Method
int value12 = Convert.ToInt32("11110100001001000000", 2);
int value13 = Convert.ToInt32("3641100", 8);

//如果懒惰可以这样写,只是性能会差一点点
int value14 = (int)decimal.Parse("1,000,000", NumberStyles.Any);

Reference data

[MSDN] NumberStyles enumerated type

[Wikipedia]Defensive programming

Original: Large column  [C #] Various quick and easy word into digital values (string to int)


Guess you like

Origin www.cnblogs.com/chinatrump/p/11516351.html