Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting float to int, with and without cast

Are these two equivalent?

float f = 3.14;
int i;
i = f; // 3

And

float f = 3.14;
int i;
i = (int) f; // 3
like image 267
George Newton Avatar asked Mar 01 '14 08:03

George Newton


People also ask

Can you convert a float to an int?

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.

What happens if you assign a float to an int?

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.

Can we convert float to int in Python?

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.


2 Answers

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.

like image 82
Violet Giraffe Avatar answered Sep 18 '22 17:09

Violet Giraffe


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.

like image 23
Lee Duhem Avatar answered Sep 17 '22 17:09

Lee Duhem