I’m currently facing an issue while trying to convert a variable from type double to int in C++. When using the static_cast or int() operator for the conversion, the result doesn’t seem to be correct. Can someone guide me on how to properly perform this conversion?
#include <iostream>
int main() {
double myDouble = 3.14;
int myInt = static_cast<int>(myDouble); // Also tried int(myDouble)
std::cout << "Value of myInt: " << myInt << std::endl;
return 0;
}
Here, the value of ‘myInt’ is always displayed as 3, even if ‘myDouble’ has a fractional value. How can I correctly perform this conversion?
>Solution :
The issue you’re facing is related to the truncation that occurs when converting a double to an int. The fractional part of the double is discarded during this conversion.
If you want to round the double to the nearest integer, you can use the round() function from the <cmath> header. Here’s an updated version of your code:
#include <iostream>
#include <cmath>
int main() {
double myDouble = 3.14;
int myInt = static_cast<int>(std::round(myDouble));
std::cout << "Value of myInt: " << myInt << std::endl;
return 0;
}
Now, std::round() is used to round the double to the nearest integer before the conversion to int takes place. This should give you the desired result.