pemo wrote:
> "Steven" <(EMail Removed)> wrote in message
> news:(EMail Removed)...
>
>>Hi,
>>
>>I am trying to find out how many digits there are in a given number.
>>The macro listed below works fine when applied to an INT, however when
>>doing Doubles with numbers > then a billion ?? It stops working.
>>
>>Anyone any idea's ?
>>
>>Thankx !
>>
>>Steven.
>>
>>
>>#include <stdio.h>
>>#include <math.h>
>>
>>#define DIGLEN(x) (x ? (int)(log10((double)(abs(x)))) + 1 : 1)
>>
>>int main(int argc, char *argv[]) {
>>int i = 123;
>>double j = 807319385.29;
>>double k = 12258983401.75;
>>
>>printf("%3d: %d\n", DIGLEN(i), i);
>>printf("%3d: %.2f\n", DIGLEN(j), j);
>>printf("%3d: %.2f\n", DIGLEN(k), k);
>>
>>return 0;
>>}
>
>
> Do you mean 'significant' digits, e.g., that 3.142 resolve to be '1'?
>
> If yes, then you probably want:
>
> #define DIGLEN(x) (x ? (int)(log10((double)(fabs(x)))) + 1 : 1)
>
> e.g., fabs instead of abs.
>
> btw, according to the latest C std, abs() is prototyped in stdlib.h, not
> math.h (fabs() is in there though)
>
>
You may have some problems with rounding...
.... and the number of digits is closely linked with a choosen (?) representation
May be you could write something like
#define DIGLEN(x, y) (x ? (int)(log10 (fabs(x)+0.5e##y)) +1 : 1)
in order to have the number of digits for printing with
printf("%3d: %.3f\n", DIGLEN(p, 3 p);
printf("%3d: %.5f\n", DIGLEN(p, 5 p); ...
Xavier
