Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert int to float in python?

Tags:

python

Does anyone know how to convert int to float.

For some reason, it keeps on printing 0. I want it to print a specific decimal.

sum = 144 women_onboard = 314 proportion_womenclass3_survived = sum / np.size(women_onboard) print 'Proportion of women in class3 who survived is %s' % proportion_womenclass3_survived 
like image 828
Mr_Shoryuken Avatar asked Nov 26 '15 17:11

Mr_Shoryuken


People also ask

Does Python automatically convert int to float?

Python 3 automatically converts integers to floats as needed.

Can convert to float Python?

We can convert a string to float in Python using the float() function. This is a built-in function used to convert an object to a floating point number. Internally, the float() function calls specified object __float__() function.


1 Answers

To convert an integer to a float in Python you can use the following:

float_version = float(int_version) 

The reason you are getting 0 is that Python 2 returns an integer if the mathematical operation (here a division) is between two integers. So while the division of 144 by 314 is 0.45~~~, Python converts this to integer and returns just the 0 by eliminating all numbers after the decimal point.

Alternatively you can convert one of the numbers in any operation to a float since an operation between a float and an integer would return a float. In your case you could write float(144)/314 or 144/float(314). Another, less generic code, is to say 144.0/314. Here 144.0 is a float so it’s the same thing.

like image 119
Y2H Avatar answered Sep 19 '22 14:09

Y2H