Search code examples
c++numberscmath

How to count decimal digits of an integer?


I wrote a program to determine the number of digits in a number

#include <iostream>
#include <cmath>
using namespace std;

int main()
{
    long long num1 = 1999999999999999;
    long long num2 = 9999999999999999;
    int number_of_digit_1 = log10(num1) + 1;
    int number_of_digit_2 = log10(num2) + 1;
    cout << number_of_digit_1 << endl;
    cout << number_of_digit_2 << endl;
}

The output is this

16 
17

Eventhough it shoudld print the same number (16). Why does this happen?


Solution

  • log10 takes various floating point types as arguments and returns the same type in its result. In your case it is converting to double.

    double only has 53 bits for it's integer (significand) part.

    9999999999999999 needs 54 bits to be represented accurately.

    When you convert 9999999999999999 to double you get 10000000000000000 so the result of 16 from log10(9999999999999999) is to be expected.

    To get an accurate (and probably faster) count of digits in an integer you should use an integer method for calculating the digits. There are various techniques for example What is the fastest method of calculating integer Log10 for 64-bit integers on modern x86-64? or http://graphics.stanford.edu/~seander/bithacks.html#IntegerLog