本文翻译自:Way to get number of digits in an int?
获取int的长度是否比这种方法更简洁?
int length = String.valueOf(1000).length();
#1楼
参考:https://stackoom.com/question/5TwF/获取int的位数的方法
#2楼
How about plain old Mathematics? 普通的老数学怎么样? Divide by 10 until you reach 0. 除以10直到达到0。
public static int getSize(long number) {
int count = 0;
while (number > 0) {
count += 1;
number = (number / 10);
}
return count;
}
#3楼
The logarithm is your friend: 对数是你的朋友:
int n = 1000;
int length = (int)(Math.log10(n)+1);
NB: only valid for n > 0. 注意:仅对n> 0有效。
#4楼
Since the number of digits in base 10 of an integer is just 1 + truncate(log10(number)) , you can do: 由于整数的基数10中的位数仅为1 + truncate(log10(数字)) ,因此您可以:
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. 编辑,因为我的上一次编辑修复了代码示例,但没有修改说明。
#5楼
Your String-based solution is perfectly OK, there is nothing "un-neat" about it. 你的基于String的解决方案完全没问题,没有什么“不整齐”的。 You have to realize that mathematically, numbers don't have a length, nor do they have digits. 你必须在数学上认识到,数字没有长度,也没有数字。 Length and digits are both properties of a physical representation of a number in a specific base, ie a String. 长度和数字都是特定基数中数字的物理表示的属性,即字符串。
A logarithm-based solution does (some of) the same things the String-based one does internally, and probably does so (insignificantly) faster because it only produces the length and ignores the digits. 基于对数的解决方案(基于字符串的)在内部执行(某些)相同的操作,并且可能更快(无关紧要)更快,因为它只生成长度并忽略数字。 But I wouldn't actually consider it clearer in intent - and that's the most important factor. 但我实际上并不认为它的意图更清晰 - 这是最重要的因素。
#6楼
Can I try? 我可以试试吗? ;) ;)
based on Dirk's solution 基于Dirk的解决方案
final int digits = number==0?1:(1 + (int)Math.floor(Math.log10(Math.abs(number))));