Are these two equivalent?
float f = 3.14;
int i;
i = f; // 3
And
float f = 3.14;
int i;
i = (int) f; // 3
A float value can be converted to an int value no larger than the input by using the math. floor() function, whereas it can also be converted to an int value which is the smallest integer greater than the input using math. ceil() function. The math module is to be imported in order to use these methods.
You can safely assign a floating point variable to an integer variable, the compiler will just truncate (not round) the value. At most the compiler might give you a warning, especially if assigning from e.g. a double or bigger type.
Converting Floats to IntegersPython also has a built-in function to convert floats to integers: int() . In this case, 390.8 will be converted to 390 . When converting floats to integers with the int() function, Python cuts off the decimal and remaining numbers of a float to create an integer.
There is no difference in the ways compiler treats these 2 cases. The resulting machine code will be the same. However, the first is implicit conversion, and the second is explicit conversion. Depending on compiler flags, you may get a warning when performing implicit conversion that loses precision.
On a side note, the literal 3.14
has type double
, which means that there's also possible precision loss in the statement float f = 3.14
. A clean way would be to write float f = 3.14f
which specifies that this is
the value 3.14 of type float
.
They are the same.
Tested with GCC 4.8.2 on 32-bit x86 system.
gcc -Wall -Wextra -Wpedantic
will NOT give any warnings while compiling this code, but with -Wconversion
it will.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With