August 7th, 2003, 06:48 PM

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
August 7th, 2003, 07:04 PM

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.
Clay Dowling
Lazarus Notes
Articles and commentary on web development
http://www.lazarusid.com/notes/
August 7th, 2003, 07:11 PM

#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.
August 7th, 2003, 07:46 PM

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?
August 7th, 2003, 09:19 PM

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
August 8th, 2003, 01:47 AM

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.
Up the Irons
What Would Jimi Do? Smash amps. Burn guitar. Take the groupies home.
"Death Before Dishonour, my Friends!!"  Bruce D ickinson, Iron Maiden Aug 20, 2005 @ OzzFest
Down with Sharon Osbourne
"I wouldn't hire a butcher to fix my car. I also wouldn't hire a marketing firm to build my website."  Nilpo