Convert String to Integer
This page was last reviewed on Sep 25, 2022.
Dot Net Perls
Convert String, Integer. A String can be converted to an Integer. The String stores the digits of a number. Some functions available do not handle invalid cases well.
TryParse benefits. We show the Integer.TryParse method as a solution to handling invalid data. It does not cause performance problems with exceptions.
Here, the input String is correctly formatted. It contains the number "123456" stored as characters. We declare the local variable "i" and then use Integer.TryParse in an If-expression.
Info After Integer.TryParse returns True, we have an actual Integer. We show this by dividing the Integer by two.
And This would not be possible with a number stored in String format. A string cannot be divided.
Module Module1 Sub Main() ' Input String. Dim value As String = "123456" ' Use Integer.TryParse. Dim i As Integer If (Integer.TryParse(value, i)) Then Console.WriteLine("Integer: {0}", i) Console.WriteLine("Half: {0}", i / 2) End If End Sub End Module
Integer: 123456 Half: 61728
Discussion. Integer.TryParse does not cause performance problems when an invalid number is encountered. This method is usually considered the best parsing method.
Also You do not have to write custom algorithms. TryParse will tell you if you have an invalid number.
Detail Integer.TryParse is probably best unless you have serious performance demands.
Summary. We converted a String holding digit characters into an actual Integer. Integer.TryParse (and other TryParse functions) is versatile and useful.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Sep 25, 2022 (edit).
© 2007-2024 Sam Allen.