Let’s have a look at a simple program to convert a numeric string to an integer.īool isTrue = int.TryParse(value, out numeric) Ĭonsole.WriteLine("The Integer value is " + numeric) It will return a value based on the success or failure of the conversion. TryParse method accepts two parameters, the first one is the string that the user wants to convert and the second parameter is the keyword “out” followed by the variable in which you want to store the value. This method doesn’t consider any blank space before or after the string but all the other string characters should be of an appropriate numeric type to facilitate a conversion.įor example, any white space, alphabet or special character within the variable can cause an error. One of the most common ways to parse a string representation into a 32-bit integer is by using the TryParse method. Here if the String variable is numeral, then it will be converted into integer but in case of an erroneous string and it will throw up an exception that will be handled by the catch block. In the above program, we used the convert method to convert a string into an integer. It can catch the exception and show the failure details.Ĭonsole.WriteLine("The converted int is : "+i) Using the Convert method is quite helpful if you want to know the reason behind the failure of the parse. For Example, if an exception occurs in a loop then a lot of memory will be consumed in throwing them and hence it will slow down your program. This method is not as simple as the previous method as we have to be ready to handle any exception that may occur due to the program interacting with erroneous data.Įxceptions can also consume a lot of memory, hence it’s not advisable to encounter any wanted or unwanted exception during the execution flow. If any character other than numeral is present then this method will throw the following error: “” System.Convert MethodĪnother way to convert a string to integer is by using the Convert method. if a string contains any characters other than numerals. The tricky part of using the int.Parse method is the problem of throwing an error if the string is not in a correct format i.e. The program will return the numerical value of the string. Let’s try a simple program to convert this string into an integer. For Example, you receive a string numeral from a user input like “99”. This method is mainly used when you have an integer in the form of string. It may throw an error if the conversion is not successful. This is one of the easiest and simplest way to convert a string to an integer. Int.Parse method works like wonders if you are sure that your conversion will never throw an error. Converting Non-Numeric String To Integer.
0 Comments
Leave a Reply. |