Skip to main content
added 85 characters in body
Source Link
Dirk
  • 31.1k
  • 8
  • 86
  • 103

Since the number of digits in base 10 of an integer is just roundup1 + truncate(log10(number)), you can do:

public class Test { public static void main(String[] args) { final int number = 1234; final int digits = 1 + (int)Math.floor(Math.log10(number)); System.out.println(digits); } } 

Edited because my last edit fixed the code example, but not the description.

Since the number of digits in base 10 of an integer is just roundup(log10(number)), you can do:

public class Test { public static void main(String[] args) { final int number = 1234; final int digits = 1 + (int)Math.floor(Math.log10(number)); System.out.println(digits); } } 

Since the number of digits in base 10 of an integer is just 1 + truncate(log10(number)), you can do:

public class Test { public static void main(String[] args) { final int number = 1234; final int digits = 1 + (int)Math.floor(Math.log10(number)); System.out.println(digits); } } 

Edited because my last edit fixed the code example, but not the description.

Source Link
Dirk
  • 31.1k
  • 8
  • 86
  • 103

Since the number of digits in base 10 of an integer is just roundup(log10(number)), you can do:

public class Test { public static void main(String[] args) { final int number = 1234; final int digits = 1 + (int)Math.floor(Math.log10(number)); System.out.println(digits); } }