Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Way to get number of digits in an int?

Tags:

java

integer

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

int numDigits = String.valueOf(1000).length(); 
like image 640
fnst Avatar asked Aug 20 '09 14:08

fnst


People also ask

How do you find the number of digits in an integer?

Perhaps the easiest way of getting the number of digits in an Integer is by converting it to String, and calling the length() method. This will return the length of the String representation of our number: int length = String. valueOf(number).

How do you extract the number of digits in a number?

Extracting digits of a number is very simple. When you divide a number by 10, the remainder is the digit in the unit's place. You got your digit, now if you perform integer division on the number by 10, it will truncate the number by removing the digit you just extracted.

How do you count the number of digits in an integer in Python?

The len() function is a built-in function in Python used to calculate the number of characters inside a string variable. The len() function takes a string as an input parameter and returns the number of characters inside that string.


1 Answers

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.

like image 145
Michael Borgwardt Avatar answered Sep 18 '22 00:09

Michael Borgwardt