Summary of three solutions for converting strings to integers in C

  • 2020-05-12 03:13:45
  • OfStack

In C#, there are basically three ways to convert a string or floating point number to an integer:
(1) use type casting :(int) floating point
(2) use Convert.ToInt32 (string)
(3) use int.Parse (string) or int.TryParse (string,out int)

When used in practice, when the string or number to be converted has a decimal, the following differences are found:
(1) method 1: truncate method 2:4 rounds 5 in
int a = (int) 2.8; // is equal to 2
int b = Convert. ToInt32 (2.8); //b has a value of 3
(2) if the parameters of the int.Parse method cannot be converted to an integer, an exception will be declared.
Such as int c = int. Parse (" 2.8 "); // returns an exception, indicating that the parameter must be an integer string
//int.TryParse
int c = -1;
int. TryParse (" 2.8 ", out c); // failed to convert, the result is 0
int. TryParse (" 2 ", out c); // the conversion is successful and the result is 2

So what happens when the information to be converted is 1 character instead of a number?
The results are as follows:
int a = (int) 'a'; // the result is 97, note that it is a character, not a string (if it is a string, the compilation cannot pass)
int b = Convert. ToInt32 (" a "); / / the anomalies
int c = int. Parse (" a "); / / the anomalies
int d = -1;
int. TryParse (" a out d); // is equal to 0

Related articles: