double to int cast and rounding issues

Andrew Haley aph@redhat.com
Fri Oct 24 08:55:00 GMT 2008


Eric Fernandez wrote:

> I have a question regarding the conversion of double to int. Considering
> this little program:
> 
> 
> #include <iostream>
> using namespace std;
> 
> int main()
> {
>   double a = 50.0;
>   double b = 48.7;
>   
>   double c = a - b;
>   
>   cout << c << endl;
>   cout << c * 10 << endl;
>   cout << static_cast<int>(c * 10) << endl;
> 
>   return 0; 
> }
> 
> 
> I get this result:
> 1.3
> 13
> 12 <--- why not 13?
> 
> 1) I am aware I may touch here the problem of floating point
> representation and that the 1.3 value - result of a subtraction - is not
> exactly this one, but maybe  1.2999999... Is this the reason why the int
> conversion transforms the "double" 13 into a "int" equal to 12 ? 

Yes.

> 2) How to avoid this problem ? I'd like to be sure to round this number
> correctly (with a precision of 1/10th, 1/100th, etc...).
> 
> I have tried to find relevant information regarding this issue but did
> not find a clear answer,

Use the round() function before static_cast<int>.

Andrew.



More information about the Gcc-help mailing list