Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Want to seperate the integer part and fractional part of float number in python [duplicate]

I am Working on Converting the value of foot to inches where 1 foot = 12 inches. I am calculating the height of person in inches. ex. 5.11 a person of height 5 foots and 11 inches means total 71 inches. Is there any way in Python so i can separate the int part & float part of float number for further calculations ? any suggestions are welcome.

like image 972
Pradeep Avatar asked Dec 18 '13 09:12

Pradeep


3 Answers

To get the integer part of a float use the built-in int() function:

>>>int(5.1)
5

To separate the float part subtract the float with the integer:

>>>5.1 - int(5.1)
0.1

Or you could get the modulus (which is the float part) of the float with 1:

>>> 5.1 % 1
0.09999999999999964 #use the round() function if you want 0.1
like image 74
K DawG Avatar answered Sep 20 '22 06:09

K DawG


For you, 5.11 is not a float. If it were, then it would mean 5.11 feet, which is 61.32 inches.

5.11 is a string containing two pieces of data and a separator - parse it like one! If you change the separator to the more conventional ' (i.e. 5'11), it becomes obvious it is not a single float:

raw = raw_input("Enter feet'inches")
feet, inches = map(int, raw.split("'", 1))
like image 39
Eric Avatar answered Sep 21 '22 06:09

Eric


Another way is to use the divmod (function or operator), using as denominator (divisor) the number 1:

>>> divmod(5.11, 1)
(5.0, 0.11000000000000032)

>>> 5.11.__divmod__(1.)
(5.0, 0.11000000000000032)
like image 39
Hugo Corrá Avatar answered Sep 20 '22 06:09

Hugo Corrá