How to count the number of digits in double/float C++

Viewed 15369

I'm trying to count the number of digits in fractional part of double, but something is going wrong and I getting infinite loop:

double pi = 3.141592;
int counter = 0;
for (; pi != int(pi); ++counter)
    pi *= 10;
cout << counter << endl;

I'v just read about this problem, however I can't find a good solution. Is there really no better way than convert a number to string and count chars? I suppose there's more correct method.

4 Answers

Atharva MR Fire here.

I've made a simple function that can count number of digits in a double.(float has 8 bits so just change 16 to 8 and make some other necessary changes.)

int get_float_digits(double num)
{
    int digits=0;
    double ori=num;//storing original number
    long num2=num;
    while(num2>0)//count no of digits before floating point
    {
        digits++;
        num2=num2/10;
    }
    if(ori==0)
        digits=1;
    num=ori;
    double no_float;
    no_float=ori*(pow(10, (16-digits)));
    long long int total=(long long int)no_float;
    int no_of_digits, extrazeroes=0;
    for(int i=0; i<16; i++)
    {
        int dig;
        dig=total%10;
        total=total/10;
        if(dig!=0)
            break;
        else
            extrazeroes++;
    }
    no_of_digits=16-extrazeroes;
    return no_of_digits;
}

If you want to get just the number of decimals, add a code no_of_digits=no_of_digits-digits; at the end, before the return function.

I hope this helps.

Related