How to Find Length of Integer Variable in C#

Last Updated on June 10, 2022 by Roshan Parihar

In this tutorial, learn how to find length of integer variable in C# or C-Sharp. The short answer is to use the myInt.ToString().Length method and replace myInt with your integer variable.

You can also use the loop to get the count of integer variable value in C#. Loop counts the digits in an integer variable in each loop one by one. However, there are some other methods with other functions that you will learn in this tutorial.

So, find out different methods to get the length of the int variable with the examples given here.

Find Length of Integer Variable Using ToString().Length Method in C#

To find the length of the integer variable, you have to use the myInt.ToString().Length method. Also, you have to change the myInt variable with your integer variable. It first converts the integer variable to the string variable using the ToString(). After that, it counts the length as given below.

Output

The length of integer variable is: 3

The above examples show the length of the integer variable as 3. It first declares the integer variable using the int data type. After that, it calculates the size of the integer variable using the method. There are three digits in a variable value. That’s why the results if the length of the integer variable is 3.

Note: The above method is not useful when you have to find the length of the integer variable. You can use the below-given methods to find the length of both positive as well as a negative integer variables.

Get Count of Int Variable Using Math.Log10() in C#

If you want to get the count of int variable in C#, you have to use the Math.Log10(). Whether the integer value is negative or positive, you can use the Math.Abs() method inside the function to convert negative to positive. Use the method given below.

Output

The length of integer variable is: 3

The above example shows that there are 3 digits in the integer variable. The method Math.Abs() first converts the negative value to positive. After that, the method Math.Log10() counts the number of digits present in the integer variable.

Using Loop to Find Length of Integer Variable in C#

In addition to the above methods, you can also use the loop to find the length of the integer variable in C#. You have to first declare the variable value and initiate the size with zero. After that, you can use the while loop that runs the loop until it reach the size of the int variable value. See the example given below to learn the method.

Output

The length of integer variable is: 3

When you check the above example, you will get the size of the variable as 3.

You May Also Like to Read

Reference

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.