How to convert int to float in python? - 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

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.

Other than John's answer, you could also make one of the variable float, and the result will yield float.
>>> 144 / 314.0
0.4585987261146497

In Python 3 this is the default behavior, but if you aren't using that you can import division like so:
>>> from __future__ import division
>>> 144/314
0.4585987261146497
Alternatively you can cast one of the variables to a float when doing your division which will do the same thing
sum = 144
women_onboard = 314
proportion_womenclass3_survived = sum / float(np.size(women_onboard))

You can just multiply 1.0
>>> 1.0*144/314
0.4585987261146497

You can literally convert it into float using:
float_value = float(integer_value)
Likewise, you can convert an integer back to float datatype with:
integer_value = int(float_value)
Hope it helped. I advice you to read "Build-In Functions of Python" at this link:
https://docs.python.org/2/library/functions.html

The answers provided above are absolutely correct and worth to read but I just wanted to give a straight forward answer to the question.
The question asked is just a type conversion question and here its conversion from int data type to float data type and for that you can do it by the function :
float()
And for more details you can visit this page.

Related

How to separate the Full number and Decimal Number from a Divison Result in Python

For python
After division, if the result has any decimal number with the full number, I just want to get the full number and ignore the decimal number.
for example:
130/33 = 3.939393
here I just want to use the number "3" and ignore the ".939393"
How can I do that?
Thanks in advance.
Use integer division:
print(130//33)
3
SEE ALSO:
Also referred to as integer division. The resultant value is a whole integer, though the result’s type is not necessarily int. The result is always rounded towards minus infinity: 1//2 is 0, (-1)//2 is -1, 1//(-2) is -1, and (-1)//(-2) is 0
Numeric Types — int, float, complex: https://docs.python.org/3/library/stdtypes.html#numeric-types-int-float-complex
What is the difference between '/' and '//' when used for division?
You can cast to int without using any library
print(int(130/33))
Documentation about casting
You can use floor method of math package.
import math
# prints floor() method
print(math.floor(130/33))
Output:
 
3

Difference between round() and float() in Python

Could someone explain me what's the difference between round() and float() in Python, please?
For example
x = 9.09128239
x = float("{0:.2f}".format(x))
y = 9.09128239
y = round(y, 2)
As I see, both functions from the code above do the same job. However, round() seems more compact and appealing to me.
I'd like to know if there is something else behind these functions and if I should consider something in particular when choosing which one to use.
Thank you for your help in advance!
It is not the float function that is doing the rounding here.
As a general term, float and round do very different things. Float takes a valid input and attempts to typecast it into a floating point representation. Round just rounds up to n significant digits.
float(3) #works on numbers
float("5.2") #and strings too!
x = 9.09128239
#x = float("{0:.2f}".format(x)) #there are two steps here.
result = "{0:.2f}".format(x)
#result is a string "9.09" The rounding happened because of the precision listed during string formatting.
x = float(result) #just takes the string and converts to float
y = 9.09128239
y = round(y, 2) #directly works on the float and rounds it off.
Tl;Dr Just use round.
This formats and parses a string, which is a lot of unnecessary work:
x = float("{0:.2f}".format(x))
This simple rounds the float, and will be much faster:
y = round(y, 2)
One of the main differences is that float is a class and round is a function. Using float does not round a number:
float('0.12345') #0.12345
but round does:
round(0.12345, 2) #0.12
Use float to convert something to a float, and use round to round off a float.
float() is used for type conversion of data to the float-type, if applicable.
On the other hand, round() is used for rounding of the given value to the specified number of decimal places.
Just as a quick note, what you are doing above in the example for float() is taking a number, rounding it off to the specified number of digits (in your example, two), converting it into string, and then type casting it into float data type.
For more information on float(), you may visit this page:
[Built in Functions](https://docs.python.org/3/library/functions.html#float)

Divide values in Python

I made a xlrd to json parsing script, which doesn't divide variables. It always returns zero... the code which I am using to divide the variables is:
if not row_values[2]:
key['nr_one'] = 0
else:
key['nr_one'] = int(row_values[2])
if not row_values[4]:
key['nr_two'] = 0
else:
key['nr_two'] = int(row_values[4])
try:
key['perc'] = float(key['nr_two']/key['nr_one']*100)
except ZeroDivisionError:
key['perc'] = 0
I have printed the following code at the end of the script:
print('one')
print(key['nr_one'])
print('two')
print(key['nr_two'])
print('perc')
print(key['perc'])
This returns:
one
103386547
two
135680054
perc
0.0
So. I don't understand why the division fails and returns 0? Could someone please help me format a good way to calculate the percentage
it should be float(key['nr_two']) /key['nr_one']*100
Integer division is like this :
1/3 #=> 0
The easiest way to understand this result is not as a fraction, but as the answer to the question "How many times do 3 fit in 1?".
So 0 multiplied by 100 is still :
1/3 * 100 #=> 0
You need
100.0*1/3 #=> 33.333333
For your code :
key['perc'] = 100.0*key['nr_two']/key['nr_one'] (without using float(...))
It returns :
76.1987808465937
NOTE: You really need to type 100.0 (a float), not just 100 (an int). You'd get 76 otherwise.
key['nr_two'] is integer and so is key['nr_one']. So when they are divided, the result is forced to be an integer in Python 2x versions (in Python 3x this limitation does not exist and your code would run just fine). What you therefore get, is 0, which is later multiplied by 100, so still 0 but float, 0.0.
To achieve float division in python 2.x you can just add:
from __future__ import division
This way you will not need to convert your numbers each time you divide them.

Convert int to double Python [duplicate]

This question already has answers here:
How can I force division to be floating point? Division keeps rounding down to 0?
(11 answers)
Closed 7 years ago.
I can't seem to find the answer to this on this site, though it seems like it would be common enough. I am trying to output a double for the ratio of number of lines in two files.
#Number of lines in each file
inputLines = sum(1 for line in open(current_file))
outputLines = sum(1 for line in open(output_file))
Then get the ratio:
ratio = inputLines/outputLines
But the ratio always seems to be an int and rounds even if I initialize it like:
ratio = 1.0
Thanks.
In python 2, the result of a division of two integers is always a integer. To force a float division, you need to use at least one float in the division:
ratio = float(inputLines)/outputLines
Be careful not to do ratio = float(inputLines/outputLines): although that results in a float, it's one obtained after doing the integer division, so the result will be "wrong" (as in "not what you expect")
In python 3, the integer division behavior was changed, and a division of two integers results in a float. You can also use this functionality in python 2.7, by putting from __future__ import division in the begging of your files.
The reason ratio = 1.0 does not work is that types (in python) are a property of values, not variables - in other words, variables don't have types.
a= 1.0 # "a" is a float
a= 1 # "a" is now a integer
Are you using Python 2.x?
Try using
>>> from __future__ import division
>>> ratio = 2/5
0.4
to get a float from a division.
Initializing with ratio = 1.0 doesn't work because with ratio = inputLines/outputLines you are re-assigning the variable to int, no matter what it was before.
Indeed, Python 2 returns an integer when you divide an integer. You can override this behaviour to work like in Python 3, where int / int = float by placing this at the top of your file:
from __future__ import division
Or better yet, just stop using Python 2 :)
You need to cast one of the terms to a floating point value. Either explicitly by using float (that is ratio = float(a)/b or ratio=a/float(b)) or implicitly by adding 0.0: ratio = (a+0.0)/b.
If using Python 2 you can from __future__ import division to make division not be the integral one but the float one.

Is there a function to convert an octal number to decimal?

I have a list of octal numbers that I want to convert into decimal; I used "%d" but it didn't work.
You can use int(str(number), base=8).
Example output:
>>> int('024', 8)
20
If you want to use integers, you can do like this.
int(str(int(number)), 8)
Based on your comment, this answer proposes a small modification on #ForceBru's answer, it appears that the numbers are formatted as floating points. Since your number is 1.0. If the numbers are in reality integers, you can do this by performing a conversion first:
>>> your_num = 1.0
>>> int(str(int(your_num)),8)
1
If your_num is a string, you can first convert it to a float and then to an int:
>>> your_num = "1.0"
>>> int(str(int(float(your_num))),8)
1
(since it is possible you parsed the number as a float. Note that you will drop the decimal part the value in such case.

Categories

Resources