C # Summary of three solutions to convert a string to an integer

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.