Way to get number of digits in an int?

fnst picture fnst · Aug 20, 2009 · Viewed 576.1k times · Source

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

int numDigits = String.valueOf(1000).length();

Answer

Michael Borgwardt picture Michael Borgwardt · Aug 20, 2009

Your String-based solution is perfectly OK, there is nothing "un-neat" about it. 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, i.e. 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.