You cannot prevent rounding errors when converting a number that is not an integer (in the mathematical sense) to an integer, the only thing you can do is try to achieve the correct rounding.
The easiest way to achieve a reasonable (though not ideal) rounding of this is as follows:
int intValue = (int)(dblValue < 0 ? dblValue - 0.5 : dblValue + 0.5);
And, of course, since your question is marked as c++ and casting , I cannot help but replace your cast in a C style with a C ++ style:
int intValue = static_cast<int>(dblValue < 0 ? dblValue - 0.5 : dblValue + 0.5);
gha.st Apr 29 '14 at 20:04 on 2014-04-29 20:04
source share