Calculating the Number of Digits in an Integer

Sometimes it can be handy to calculate the number of digits in an integer for various mathematical calculations.

In C++

#include <math.h>
 
double len(double n) {
        if n == 0:
                 return 1
 
        double l = floor ( log10 ( n ) ) + 1; /* Number of digits in n */
        long unsigned int len = int(l); /* Save it to an integer instead */
 
        return len;
 
}

In Python

from math import log10, floor
 
def length(n):
     if ( n == 0 ) { return 1; }
     return floor( log10( n ) ) + 1

7 Responses to “Calculating the Number of Digits in an Integer”

  1. Elliott C. Bäck Says:

    Check this out for a few interesting C bit hacks: http://graphics.stanford.edu/~seander/bithacks.html

  2. nlindblad Says:

    Awesome, thanks Elliott :)

  3. Jon Says:

    log10(0) is undefined, so this function should be modified to return 1 if n == 0

  4. nlindblad Says:

    Good point :)

  5. Afterlife(69) Says:

    And in php: $digits = strlen($int); :)

  6. nlindblad Says:

    @Afterlife(69): That’s not mathematical :)

  7. Afterlife(69) Says:

    xD its easy tho ;)

Leave a Reply