# Thread: strlen for nummeric types?

1. ## strlen for nummeric types?

Please imagine size is a variable and could be also a long double with 2.000.000.
Code:
```	int size = 50;
char size_as_chararray[8000];
sprintf(size_as_chararray, "%d", size);```
How to allocate the size of the char array more elegant? I think for allocating exactly what it needs I would need to know the length of variable size.

I need something like
int size = 100.000
strlen(size) --> 6 (Numbers)

double size = 555555555
strlen(size) --> 9

Well, obviously I can't covert into char array first and use strlen then because converting into char array is the thing I originally wanted to do.

Is there some function to get the amount of numbers of a numeric type?

2. Well, yes: 1+floor(log10(num)) is the number of decimal digits in the whole-number part of num. (So that's why your 11th grade teacher went on and on and on about logs. Now we know.)

3. Code:
```#include <float.h> /** limit constants for floating points **/

char text[LDBL_DIG]; /** at least 10, the most you ought to need **/
int d = foo();

sprintf(text, "&#37;d", d);```

4. Originally Posted by tabstop
Well, yes: 1+floor(log10(num)) is the number of decimal digits in the whole-number part of num.
And what if num is negative ? Or num is zero ?

A "strlen"-like function for integer would make sense because there's basically only one notation for them, but it's a bit different for floating point numbers where scientific notation is used.

So, to solve your problem, declare an array of around 50 characters, use only scientific notation for floating-point number and you shouldn't have any problem with your code for at least a couple of decades.

5. Originally Posted by foxman
And what if num is negative ? Or num is zero ?
Throw away the i*pi part and just use the real part of the logarithm . And now that there's only one special case, it's easy to check for zero.

6. A "strlen"-like function for integer would make sense because there's basically only one notation for them,
C++ allows three different notations for integer literals. And it doesn't even support binary.

7. If you need to do this a lot, there's a much more efficient method which takes at most 4 comparisons.