casting double to unsigned int

Jul 3, 2008 at 11:00am
hi guys,

how do i use casting for a double type number to correctly change into unsigned int type number

for example:
1
2
double dbl = 7.9992;
unsigned int UInt = (unsigned int)dbl;


here i want UInt to be 8 instead of 7, which is the case right now. how do i do that without to use my own function?
Jul 3, 2008 at 11:07am
The only way I've seen to do it is to add 0.5 before casting. Also, if you're in C++ rather than C, you'd be better using static_cast. So your code would look like this:

1
2
double dbl = 7.9992;
unsigned int UInt = static_cast<unsigned int>(dbl + 0.5);
Jul 3, 2008 at 11:15am
thanks bnbertha for the quick reply. now i remember a bit. by adding 0.5, then floor rounding is always mathematically correct to the original ones, am i right? this must be caused of lacks of practices. thanks bnbertha!
thanks for the tips about static_cast too!
Jul 3, 2008 at 11:32am
Yes, then flooring works for you.

No problem
Topic archived. No new replies allowed.