# Thread: Why does this not work???

1. ## Why does this not work???

This code is supposed to tell me the number of digits to the right of the decimal. It works sometimes (with some numbers), and other times it just sits there and I have to shut it down with my task manager (program not responding). I thought it may be getting stuck in the outer for loop, so that's why I have the escape things commented out in there... Some examples, it works for .25, but not for .3, what's going on??

Thanks,
Sean
SeanMSimonsen@cs.com

int Decimals(double number) // Tells how many digits are to the right of the decimal in a number
{
int decimals = 0;
// int escape = 0;

for( ; /* escape == 0 */; )
{
for( double counter = 0; ; counter++ )
{
if( counter >= number )
{
break;
}
}

if( number != counter )
{
decimals++;
number *= 10;
}
else
break; /* escape = 1; */
}

return decimals;
}

2. Your problem is probably that you need floating point numbers to be more precise than they actually are. You can't rely testing for equality as the internal representation may differ very slightly. You could do something like this (although you'd be limited in the number of decimal points you can count) -

Code:
```int Decimals(double number) {

int num = number*1000000000;
for (int i=0,j=1000000000;num>0;i++,j/=10)
{
num%=j;

}

return i-1;
}```

3. Here try this code.

int NumDecimals (double Value)
/* Pre: Value > 0 and has decimals
Post: Number of decimals is returned */
{
int NumDecimals = 0;
while (Value > 0)
Value--;// while
// Now value is 0.###
Value *= 10; // Move the decimal one over
while (Value > 0)
{
NumDecimals++;
while (Value > 0)
Value--;// while
Value *= 10;
}// while
return (NumDecimals);
}

Try that its purely experimental but it should work.

http://home.dencity.com/neoprogramming/index.html