Skip to main content

C++ Double to Int

In day to day programming we will need to convert a double value to an int value in different use cases. Also, I'm going to talk about how to avoid compiler warning C4244 when converting double to int.

Implicit Conversion


C Style Casting


However for both above some compilers will give a compiler warning as below. You can use below static_cast method to avoid that.

warning C4244: '=': conversion from 'double' to 'int', possible loss of data

Static Cast


I personally use this method to avoid compiler warnings. Make sure to remember all above three methods will truncate the value. That means the decimal part will cut off.

If you want to round the number to the nearest integer you can use one of below methods.

Manually Add or Subtract 0.5


If the number is positive you need to add 0.5 and convert to int using any of the above methods. If the number if negative you need to subtract 0.5 and convert to int using any of the above methods.

Use std::round


You can use std::round method to round the number and convert to int.

Also, based on your requirement you can use std::floor, std::ceil, std::trunc methods. Please click on the link to read more on those methods. Make sure to include cmath if you use std::round or any of the these methods.