# Thread: infinite loop on floating point number

1. ## infinite loop on floating point number

The following code is used to get the number of decimal places after the decimal point, but can go into an infinite loop sometimes on my compiler:
g++ (GCC) 4.1.2 20080704 (Red Hat 4.1.2-48)

The questions are
1) why does a double like 134.29 triggers an infinite loop? some floating point numbers cause such infinite loop, but most other floating point numbers just work fine. Are there any rules of thumb on the numbers which cause the infinite loop?
2) baring using string length to get the number of decimal places, is there any other way to improve the existing code to avoid triggering the infinite loop?

Code:
```#include <iostream>

int main()
{
double data=134.29;

double v = data;
int8_t dpcount = 0;
static double EPS=1E-3;

while(v - (int)v  > EPS)
{
v *= 10;
++dpcount;
std::cout<< "data: " << data <<  " v: "<< v << " dpcount: " << (int) dpcount << std::endl;
}
}```

Thanks 2. You are seeing floating point inaccuracies. The value .29 can not be properly represented in binary so what this is actually something like: .28999999999999204. It also looks like your equation in your if statement is incorrect. I think you should be using the < operator instead of the > operator. This link seems to explain the issue very well.

Jim Code:
`cout << int(v) << endl;`
to the loop, it looks like the actual value of data is just under what it should be, e.g. something like 134.289999999. The behavior of int(v) is to round down so the difference (v - int(v)) ends up being close to 1, rather than 0.

A quick way to make int(v) round up in these cases is to add a small amount to v (and also use abs)
Code:
`while (abs(v - int(v+.5)) > EPS)` 4. Don't convert to int and then back to float just to get the non-integral portion of the value.
Use the function called floor for that. Firstly it's much faster than converting both ways and also it still works when the value of the double exceeds that of an int. Popular pages Recent additions 