首页 > 开发 > 综合 > 正文

Numeric Parse Method

2024-07-21 02:16:37
字体:
来源:转载
供稿:网友
the parse method converts a string that represents a .net framework numeric base type to an actual .net framework numeric base type. it takes the following forms, where xxx is the name of the numeric base data-type class:

public static xxx parse(string s);
public static xxx parse(string s, numberstyles style);
public static xxx parse(string s, numberstyles style, numberformatinfo info);
the parse method takes a combination of three parameters: the string to be converted, one or more values from the numberstyles enumeration , and a numberformatinfo class. all numeric strings produced by the parse method, except hexadecimal strings, will always be parsable by this method. because the parse method assumes that all string input represents a base-10 value, no non base-10 values are parsable. it will also not parse strings that represent the values nan, positiveinfinity, or negativeinfinity of the single and double classes because they are not real numbers.

the following example converts a string to an int value, increments that value, and displays the result.

[c#]
string mystring = "12345";
int myint = int.parse(mystring);
myint++
console.writeline(myint);
//results in "12346"
the numberstyles enumeration is usefull if you have a string that contains non-numeric characters that you want converted into a .net framework numeric base type. for example, a string that contains commas, parentheses, or currency symbols cannot be converted to an int value under the parse method if the numberstyles enumeration is not used. the following code is invalid and will raise an exception with the message, "the input string wasn't in the correct format."

[c#]

string mystring = "123,456";
int myint = int.parse(mystring);
console.writeline(myint);
//raises exception
when you apply the numberstyles enumeration with the allowthousands flag, the parse method will ignore the comma that raised the exception in the previous example. the following example uses the same string as the previous example, but does not raise an exception.

[c#]

string mystring = "123,456";
int myint = int.parse(mystring, numberstyles.allowthousands);
console.writeline(myint);
//results in "123456"
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表