number of digits in a number java code example

Example 1: how to get length of integer in java

int length = (int) (Math.log10(number) + 1);

Example 2: find number of digits in a number java

(int)Math.floor(Math.log10(Your_number_name_goes_here) + 1);

Example 3: count the number of digits in an integer in java

import java.util.Scanner;
public class CountingDigitsInInteger {
   public static void main(String args[]){
      Scanner sc = new Scanner(System.in);
      int count = 0;
      System.out.println("Enter a number ::");
      int num = sc.nextInt();
      while(num!=0){
         num = num/10;
         count++;
      }
      System.out.println("Number of digits in the entered integer are :: "+count);
   }
}

Example 4: how to get length of integer in java

int length = 0;
long temp = 1;
while (temp <= number) {
    length++;
    temp *= 10;
}
return length;

Tags:

Java Example