HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaCritical

Way to get number of digits in an int?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
digitsintwaynumberget

Problem

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

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

Solution

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.

Context

Stack Overflow Q#1306727, score: 419

Revisions (0)

No revisions yet.