Fastest way to get number of digits on a number? [duplicate]

喜你入骨 提交于 2019-11-30 05:05:55
Math.floor(Math.log10(number) + 1)
// or just (int) Math.log10(number) + 1

For example:

int number = 123456;
int length = (int) Math.log10(number) + 1;
System.out.println(length);

OUTPUT:

6

how about this homebrewed solution:

int noOfDigit = 1;
while((n=n/10) != 0) ++noOfDigit;

Try this :

Working Example

public class Main {
    public static void main(String[] args) {
        long num = -23;
        int digits = 0;
        if (num < 0) 
            num *= (-1);
        if (num < 10 && num >= 0)
            digits = 1;
        else {
            while(num > 0) {
                num /= 10;
                digits++;
            }
        }
        System.out.println("Digits: " +digits);
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!