Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert double to int in C++ without round down errors

I have the following codes to cast a double into an int:

double dblValue = 7.30;
int intValue = (int)(dblValue*100);  //I want intValue to store exactly 730;
std::cout << intValue;

Output: 729

I know that the compiler is reading dblValue as 7.2999999 before casting it to int.

My question is: Is it possible to cast it as 730 by preventing the round down errors?

It would be best if your solution avoid using C++11 or other predefined functions. The only pre-processor directive I am using here is <iostream>.

like image 614
user3437460 Avatar asked Apr 29 '14 20:04

user3437460


1 Answers

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 proper rounding.

The easiest way to achieve a sensible (although not perfect) rounding is the following:

int intValue = (int)(dblValue < 0 ? dblValue - 0.5 : dblValue + 0.5);

And of course, since your question is tagged both c++ and casting I cannot resist replacing your c-style cast with a c++ style cast:

int intValue = static_cast<int>(dblValue < 0 ? dblValue - 0.5 : dblValue + 0.5);
like image 68
gha.st Avatar answered Oct 12 '22 12:10

gha.st