### Thread: Is their a way to find out what place the highest # is

1. #### Is their a way to find out what place the highest # is

If I have a number, lets say 1016, is their a way to tell what place the highest # is on, like in that, the 1 is 1000, I want to find out how many digits a num is, 1016 = 4, 403 = 3, 11 = 2, 3343 = 4.. etc
2. No Profile Picture
Contributing User
Devshed Newbie (0 - 499 posts)

Join Date
Oct 2002
Location
Flint, MI
Posts
328
Rep Power
16
If I understand what you are asking (which is questionable), you could easily get this by converting the number to a string and taking the string length.

If you really don't want to drop to this level, locate the number between powers of ten and you'll have the number of digits.
3. #include <math.h>

int main()
{
int value = some_positive_value();
int digits = (int)(floor(log10(value))) + 1;
}

There are some caveats on this;

1) Won't work on negative values.
2) It assumes that all integer values that can be stored in an int can also be represented as distinct floating point values. That is not always true (particularly for larger values) as it depends on floating point precision on your machine.

If you want something that is guaranteed for all (positive) ints, consider using sprintf to write the value to a string and literally count the number of digits.
4. I am converting to string and using strlen now, I want to do it another way and it has to work for negatives.

"locate the number between powers of ten and you'll have the number of digits."

How do I go about doing this?
5. divide by 10,if the answer is greater than 1 it has a 10's place, divide same number by 100, if answer is greater than 1 it has a 100's place...rinse,repeat.
Code:
```x = num; //number being converted
y = 0;   //counter
z = 1;   //10's position
while(num/z >= 1)
{
z *= 10;
y++;
}
//y contains number of digits```
6. To handle negative numbers, you can modify grumpy's code by adding the abs() function into the expression.
Code:
```#include <stdlib.h>
#include <math.h>
int main()
{
int value = some_value();
int digits = (int)(floor(log10(abs(value)))) + 1;
}```
Another way is to note that the printf() family returns the number of characters actually output. So, you can simply sprintf() the number to a char buffer and the return value of sprintf() is the # of digits.
Code:
```#include <stdlib.h>
#include <stdio.h>
int main()
{
int value = some_value();
char buf[50];
int digits = sprintf(buf, "%d", abs(value));
}```
Last edited by Scorpions4ever; August 8th, 2003 at 01:50 AM.