Convert Double to Int in C++

In C++, you can convert a double to an int using either type casting operators or the round function in the math.h header file.

  1. Utilize type conversion operators:
double num = 4.6;
int result = static_cast<int>(num);
  1. Use the round function in the math.h header file.
#include <cmath>

double num = 4.6;
int result = round(num);

Both methods can convert a double type variable to the closest integer value. It is important to note that when using the type conversion operator to convert double to int, the decimal part is directly truncated without rounding. However, when using the round function, it will round the value.

bannerAds