number of decimals in integer
-
Is there any function which returns number of decimals in the integer, or can sombody help me with fast algorithm to do this. thanks
int digits = log10(integer) + 1;
Only works with positive numbers. HTH
[
](http://www.canucks.com)Sonork 100.11743 Chicken Little "You're obviously a superstar." - Christian Graus about me - 12 Feb '03 Within you lies the power for good - Use it!
-
Is there any function which returns number of decimals in the integer, or can sombody help me with fast algorithm to do this. thanks
pepevejlupek wrote: Is there any function which returns number of decimals in the integer Trick questions should probably be directed to the lounge. The number of decimals in an integer is always zero.
-
Is there any function which returns number of decimals in the integer, or can sombody help me with fast algorithm to do this. thanks
int CountDigits(int value)
{
int digit_count = 0;do { digit\_count++; value /= 10; } while (value != 0) { return digit\_count;
}
or, even faster:
int CountDigitsFaster(int value)
{
int digit_count = 1;
if (value < 0) value = -value;
if (value > 9) digit_count++;
if (value > 99) digit_count++;
if (value > 999) digit_count++;
if (value > 9999) digit_count++;
if (value > 99999) digit_count++;
if (value > 999999) digit_count++;
if (value > 9999999) digit_count++;
if (value > 99999999) digit_count++;
if (value > 999999999) digit_count++;
return digit_count;
}Note that
CountDigitsFaster
assumes thatint
's are 32-bit signed values. Both functions assume that the minus sign in negative values is not considered a 'digit'. If you're actually trying to compute the number of characters required to display the value, then you would have to take that into account as well.CountDigitsFaster
looks like dumb code, but is significantly faster than any alternative I can think of. It requires 10 compares, 10 jumps, possibly a negation, and up to 9 increments. My originalCountDigits
, while it may exit with an early out for small values, requires an increment and a division per iteration, for up to 9 iterations.
Software Zen:
delete this;
-
pepevejlupek wrote: Is there any function which returns number of decimals in the integer Trick questions should probably be directed to the lounge. The number of decimals in an integer is always zero.
Subtle, dude :cool:.
Software Zen:
delete this;