Convert double to int in C ++ without rounding errors

I have the following codes for casting a double to int :

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

Conclusion: 729

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

My question is : can it be sent as 730, preventing rounding errors?

It would be better if your solution avoided using C ++ 11 or other predefined functions. The only preprocessor directive I use here is <iostream> .

+5
c ++ double casting int
Apr 29 '14 at 20:00
source share
4 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 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); 
+13
Apr 29 '14 at 20:04 on
source share

You can define your own integer truncation function, which increments the value by the smallest possible value to ensure that the rounded result exceeds the threshold value.

 #include <limits> int int_cast(double x) { return (int)(x * (1.0 + std::numeric_limits<double>::epsilon())); } 

If you don't want to depend on <limits> , you can use DBL_EPSILON from <float.h> or replace your very small number. See also this question .

+1
Apr 29 '14 at 21:30
source share

This is not any type of error, as the computer saves floating point values. You can do something like this:

 int intValue = (int)(dblValue*100 + 0.00001); 
0
Apr 29 '14 at 20:04 on
source share

C ++ 11 added lround , which helps to avoid loss of precision with implicit doubling and long truncation:

 int intValue = (int) lround(dblValue*100) 

long before int casting will also not lose precision.

Unfortunately, no iround() .

Update

I think there is no iround() , because any 32-bit integer will fully correspond to 52 precision bits of a 64-bit double. Thus, there is no possibility of precision loss with direct doubling before truncating int:

 int intValue = (int) round(dblValue*100) 
-one
Aug 14 '16 at 18:38
source share



All Articles