想在python中分离浮点数的整数部分和小数部分

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20654141/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 20:57:32  来源:igfitidea点击:

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

pythonpython-2.7

提问by Pradeep

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.

我正在将英尺的值转换为英寸,其中 1 英尺 = 12 英寸。我正在计算人的身高(以英寸为单位)。前任。5.11 一个身高 5 英尺 11 英寸的人意味着总共 71 英寸。Python 中有什么方法可以将浮点数的 int 部分和 float 部分分开以进行进一步计算吗?欢迎提出任何建议。

回答by K DawG

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

要获取浮点数的整数部分,请使用内置int()函数:

>>>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:

或者,您可以使用 1 获取浮点数的模数(即浮点数部分)

>>> 5.1 % 1
0.09999999999999964 #use the round() function if you want 0.1

回答by Eric

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

对你来说,5.11不是一个浮点数。如果是,那么这将意味着 5.11 英尺,即 61.32 英寸。

5.11is a stringcontaining 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:

5.11是一个包含两条数据和一个分隔符的字符串- 像解析一样解析它!如果将分隔符更改为更传统的'(即5'11),很明显它不是单个浮点数:

raw = raw_input("Enter feet'inches")
feet, inches = map(int, raw.split("'", 1))

回答by Hugo Corrá

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

另一种方法是使用 divmod(函数或运算符),使用数字 1 作为分母(除数):

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

>>> 5.11.__divmod__(1.)
(5.0, 0.11000000000000032)