Changing double to int using casting

double newnumber=234999

1
2
  int temp=(int)newnumber;
  cout<<temp;


when I output temp I get 234998...can someone explain why?
Last edited on
Most likely the reason is that 234999.0 cannot be perfectly represented in double-precision floating-point format, and instead it is represented as a vlue just slightly less than 234999.0 (e.g. 234998.999999999...) - thus, when you perform the cast, you simply chop off the decimal digits instead of rounding. Try int temp = int(newnumber+0.5) for traditional rounding.
Use std::lround() for rounding away from zero. (usually implemented as an intrinsic).
http://en.cppreference.com/w/cpp/numeric/math/round

1
2
3
4
5
6
7
8
#include <iostream>
#include <cmath>

int main()
{
    for( double d : { -1.52, -1.49, 234999.5, 234999.0 } )
        std::cout << std::lround(d) << '\n' ;
}

http://coliru.stacked-crooked.com/a/62cafab940dac4e3
Thank you...I hadn't thought about that!
Topic archived. No new replies allowed.