I need to count the number of digits in an integer input by the user. In other words if the user enters 101010, I need to obtain the value of 6, because there are 6 digits in this number. Can someone help me
Convert the integer to a string and use the Length property. If you are using an input from a textbox or inputbox, it's already a string. Then just do this:
Private
Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim N As Integer
N = TextBox1.Text.Length
TextBox2.Text = N.ToString
End Sub
If it's a console application, the input variable assigned with Console.ReadLine is a also a string.
I'd wrap the function up in a method and place in a class library so you can easily reuse this in your applications. The only reason I suggest wrapping it up in a function is that I figure you will probably reuse this function. Also the input parameter is a integer and the return value is an integer also. You can change the input to string and remove the .tostring call
Function DigitCount(byval int_Value as integer) as integer
if int_Value.tostring.length > 0 then Return int_Value.tostring.length else Return 0 end if
End Function
In the next release of VB you will have something called extension methods which will allow you to create additional methods for system types - so can create you own NumberOfCharacters method which you can use on standard system numeric types such as integer etc.
counting digits in an integer
bpeikes
Convert the integer to a string and use the Length property. If you are using an input from a textbox or inputbox, it's already a string. Then just do this:
Private
Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim N As IntegerN = TextBox1.Text.Length
TextBox2.Text = N.ToString
End SubIf it's a console application, the input variable assigned with Console.ReadLine is a also a string.
Philip W
I'd wrap the function up in a method and place in a class library so you can easily reuse this in your applications. The only reason I suggest wrapping it up in a function is that I figure you will probably reuse this function. Also the input parameter is a integer and the return value is an integer also. You can change the input to string and remove the .tostring call
Function DigitCount(byval int_Value as integer) as integer
if int_Value.tostring.length > 0 then
Return int_Value.tostring.length
else
Return 0
end if
End Function
In the next release of VB you will have something called extension methods which will allow you to create additional methods for system types - so can create you own NumberOfCharacters method which you can use on standard system numeric types such as integer etc.