Question

Can someone explain me why in c++ happens such a thing:

double tmp;
...                    // I do some operations with tmp 
                       // after which it has to be equal to one
cout << tmp;           // prints 1
cout << trunc(tmp);    // prints 0
cout << trunc(tmp*10); // prints 9

I am using this for separation part right of decimal part from the number for example if i have: 5.010 ... i want to have 0.010 .. so I am using:

double remainder = tmp - trunc(tmp);

I am posting the whole code....the suggestion with floor does not worked

short getPrecision(double num, short maxPrecision) {

  // Retrieve only part right of decimal point
  double tmp  = fabs(num - trunc(num));
  double remainder = tmp;

  // Count number of decimal places
  int c = 0;
  while (remainder > 0 && c < maxPrecision) {
    tmp *= 10;
    remainder = tmp - trunc(tmp);
    c++;
  }
  return c;
}

When I run this function for example with 5.1 the remanider is 0 instead of 1

Was it helpful?

Solution

After some calculations it has to be one? Well, it could as well be 0.99999999999999999. Floating point operations are not precise, you should always take that into account.

OTHER TIPS

Please see picture at http://en.cppreference.com/w/cpp/numeric/math/trunc. The chart there explains the inconsistency with truncing 1. Probably the same applies to 10 as well

This should help you achieving what you need:

double remainder = tmp - floor(tmp);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top