Summary of three solutions for converting strings to integral types in C #

Source: Internet
Author: User

In C #, there are basically three ways to convert a string or floating-point number to an integer:

(1) Use coercion type conversion: (int) floating-point number

(2) using Convert.ToInt32 (String)

(3) using Int. Parse (string) or int. TryParse (string,out int)

When used in practice, when strings or numbers to be converted have decimals, they are found to have the following differences:

  (1) Method One: Truncation method two: rounding
int a= (int) 2.8; Result is 2

int B=convert.toint32 (2.8); The value of B is 3

  (2) Int. The argument of the parse method is reported as an exception if it cannot be converted to an integer.
such as int c=int. Parse ("2.8"); Report an exception stating that its argument must be an integer string

Int. TryParse

int c =-1;

Int. TryParse ("2.8", out c); Cannot convert successfully, result is 0

Int. TryParse ("2", out c); Conversion succeeded with a result of 2

So what happens when the information you want to convert is a character instead of a number?

The results are as follows:

int a = (int) ' A '; The result is 97, the note is a character, not a string (if it is a string, compilation cannot pass)

int B = Convert.ToInt32 ("a"); Report Abnormal

int C=int. Parse ("a"); Report Abnormal

int d =-1;

Int. TryParse ("A", out d); 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.