Q:
Hi,
Do you know a way that I could count or get the number of precision digits
of a double value in C?
For example: 123.456789 would return 6
Thanks!
A:
Here is a simple sample program:
#include <stdio.h>
#include <math.h>
int precision(double d){
int i;
if( d < 0 )d = -d;
d -= floor(d);
i = 0;
while( d > 0 ){
d *= 10;
d -= floor(d);
i++;
}
return i;
}
main(){
double d;
printf("the number:");
scanf("%lf",&d);
printf("\nthe precision is %d\n",precision(d));
}
NOTES:
The precision of the example number 123.456789 is not 6 but rather 9. What
do you expect for 0.123456789E+3 ?
Do not be surprised if you get large numbers as a result, because
123.456789
may be stored internally as
123.4567889999999999999999999999999999999
because the numbers internally are stored binary. Therefore the task is
quite indefinit.
Regards,
Peter
[ back to toc ]