In C #, there are basically three methods to convert a string or floating point number to an integer:
(1) Use forced type conversion: (int) floating point number
(2) Use Convert. ToInt32 (string)
(3) Use int. Parse (string) or int. TryParse (string, out int)
In actual use, when the strings or numbers to be converted carry decimal places, they are found to have the following differences:
(1) Method 1: truncation method 2: Rounding
Int a = (int) 2.8; // The result is 2.
Int B = Convert. ToInt32 (2.8); // The value of B is 3
(2) If the int. Parse method parameter cannot be converted to an integer, an exception is reported.
For example, int c = int. Parse ("2.8"); // if an exception is reported, the parameter must be an integer string.
// Int. TryParse
Int c =-1;
Int. TryParse ("2.8", out c); // The conversion fails and the result is 0.
Int. TryParse ("2", out c); // The conversion is successful and the result is 2.
So what if the information to be converted is a character rather than a number?
The result is as follows:
Int a = (int) 'A'; // The result is 97. Note that it is a character rather than a string. (if it is a string, compilation fails)
Int B = Convert. ToInt32 ("a"); // an exception is reported.
Int c = int. Parse ("a"); // an exception is reported.
Int d =-1;
Int. TryParse ("a", out d); // The result is 0.