Compute the number of digits in an integer

2

The title of this blog post might seem strange, but I occasionally need to compute the number of digits in a number, usually because I am trying to stuff an integer value into a string. Each time, I have to derive the formula from scratch, so I am writing this article so that I and others can look up the formula next time we need it.

The problem: You have a positive integer, n, which has k digits. How can you efficiently find k as a function of n?

The solution is to use logarithms. Because n has k digits,
10k-1n < 10k, or
10k-1 < n+1 ≤ 10k.

Applying the base-10 logarithm produces
k-1 < log10(n+1) ≤ k.

The CEIL function in Base SAS computes the integer value greater or equal to its argument, which proves that
k = ceil( log10(n+1) ).

A canonical example, is n=1234, which has k=4 digits. How can you find k from n? The following program computes k:

data _null_;
n = 1234;      /* positive integer */
k = ceil(log10(n+1)); 
put "The integer " n= "has " k= "digits.";
run;
The integer n=1234 has k=4 digits.

If you have a negative integer m ≤ -1 and the absolute value has k digits, then m requires a string with k+1 elements, because one element is needed for the negative sign.

Incidentally, there is nothing special about base 10. The proof generalizes to compute the number of digits required to represent a number in any base. For example, the number n=1234 written in base 2 requires k = ceil(log2(n+1)) = 11 digits. You can check that the 11-digit binary number 10011010010 equals the decimal value 1234.

You can also use these mathematical ideas to compute the next power of 2 (or power of 10) that is larger than a given number.

Share

About Author

Rick Wicklin

Distinguished Researcher in Computational Statistics

Rick Wicklin, PhD, is a distinguished researcher in computational statistics at SAS and is a principal developer of SAS/IML software. His areas of expertise include computational statistics, simulation, statistical graphics, and modern methods in statistical data analysis. Rick is author of the books Statistical Programming with SAS/IML Software and Simulating Data with SAS.

2 Comments

  1. If one prefers floors to ceilings:

    For n to have k digits,

    10^{k-1} ≤ n < 10^k

    k-1 ≤ log_{10}(n) < k

    k ≤ 1 + log_{10}(n) < k + 1

    So k is floor(1 + log_{10}(n))

Leave A Reply

Back to Top