How to get number of digits from an int in Java

3 Answers

0 votes
package javaapplication1;
 
public class Example {
    public static void main(String[] args) {
        
        int n = 78910;
        int count_digits = (int)(Math.log10(n) + 1); // for n > 0
        
	    System.out.format("count_digits = %d\n", count_digits);
    }
}
 
 
/*
run:
  
count_digits = 5
  
*/

 



answered Mar 21, 2016 by avibootz
edited Mar 21, 2016 by avibootz
0 votes
package javaapplication1;
 
public class Example {
    public static void main(String[] args) {
        
        int n = 78910;
        int count_digits = String.valueOf(n).length();
        
	    System.out.format("count_digits = %d\n", count_digits);
    }
}
 
 
/*
run:
  
count_digits = 5
  
*/

 



answered Mar 21, 2016 by avibootz
edited Mar 21, 2016 by avibootz
0 votes
package javaapplication1;
 
public class Example {
    public static void main(String[] args) {
        
        int n = 78910;
        int digits = count_digits(n);
        
	    System.out.format("digits_count = %d\n", digits);
    }
    
    static int count_digits(int n)
    {
	    int i;
 	    n = Math.abs(n);
	    for (i = 0; n > 0; i++)
		    n /= 10;
	    return i;			
    }
}
 
 
/*
run:
  
digits_count = 5
  
*/

 



answered Mar 21, 2016 by avibootz

Related questions

2 answers 162 views
4 answers 317 views
2 answers 115 views
1 answer 112 views
1 answer 164 views
1 answer 187 views
1 answer 163 views
...