Way to get number of digits in an int?

后端 未结 30 1354
梦毁少年i
梦毁少年i 2020-11-22 17:21

Is there a neater way for getting the number of digits in an int than this method?

int numDigits = String.valueOf(1000).length();
30条回答
  •  感动是毒
    2020-11-22 17:45

    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.

提交回复
热议问题