my_var = (int)my_var;
As simple as that. Basically you don't need it if the variable is int.
Answer from Zach P on Stack OverflowDoes C allow implicit casting/conversion from float to an int?
Converting float to int can be undefined behavior and how to fix it
Convert a Float number to an Int type
Are int to float conversions slow?
How to convert float to int in C?
How can I safely convert float to int in C?
Is math.h required for float to int conversion?
Videos
In Java it is not allowed, is it allowed in C? Why so?
Have you ever written code like this?
void foo(float f) {
int i0 = f;
int i1 = int(f);
int i2 = static_cast<int>(f);
}All of these conversions are undefined behavior if the float is out of bounds for the int. [0]
This is surprising, easy to miss and badly designed as there is no standard way of safely performing this conversion. In practice you will get an unspecified int because compilers emit the corresponding converting assembly instruction but UB is still bad and should be avoided.
I wrote a small library to fix this https://github.com/e00E/cpp-clamp-cast .
With it the previous unsafe code can be turned into the safe
void foo(float f) {
int i = clamp_cast<int>(f);
}[0] https://en.cppreference.com/w/cpp/language/implicit_conversion section "Floating–integral conversions":