我正在寻找一个问题的答案,但无论搜索多少次都无法解决。
如果...
a = 1.23
我希望能将数字1乘以一个小数0.23,该如何实现呢?
谢谢您的帮助!
在munkhd的回答评论中,您说:
我希望能够输入一个小时值,然后将其转换为分钟。因此,如果是1.20,我会将1乘以60再加上20。我相信一定有更简单的方法:)
因此,您的程序将作为字符串接收1.20。因此,您可以对其使用字符串方法,例如
>>> dotted_time = '1.20'
>>> h, m = [int(s) for s in dotted_time.split('.')]
>>> print h, m
1 20
>>> minutes = 60*h + m
>>> hours = minutes / 60.0
>>> print minutes, hours
80 1.33333333333
另外,您可以执行 colon_time = dotted_time.replace('.', ':')
; colon_time
的格式适用于标准时间函数,能够为您理解和操作。这可能是更加明智的方式,并且它可以轻松处理带有秒的时间,比如 '1.20.30',.replace('.', ':')
将其转换为 '1:20:30'。
除了PM 2Ring的答案似乎解决了[1]你实际的问题,你也可以“索引浮点数”,当然在将其转换为字符串后,但要注意有限的精度。因此,请使用内置的round
函数来定义您的解决方案所需的精度:
s = str(round(a, 2)) # round a to two digits
现在,您可以对它应用所有的字符串函数。之后,您可能需要将结果转换回float
或int
类型...
[1]其他人已经建议过了:在像Python这样的高级语言中处理常见模型,如时间,应该期望得到已经存在的可靠解决方案的支持。
使用 modf()
函数获取整数和小数部分。 modf()
将返回一个元组,包含(小数,整数)。 使用 round()
函数来控制答案的精度。
>>> import math
>>> a = 1.23
>>> math.modf(a) (0.22999999999999998, 1.0)
>>> math.modf(a)[0] #the zeroth location of the tuple is the fractional part
0.22999999999999998 # some precision lost, use round() to fix
>>> round(math.modf(a)[0], 2)
0.23 # This is an exact match the source fractional part
def get_pos_float(num, unit, precision=3):
if unit >= 10:
num = abs(round(math.modf(num)[0], 3)) # Get just the fractional part
num *= 10 # Move the decimal point one place to the right
return get_pos_float(num, unit/10)
retVal = int(math.modf(num)[1]) #Return the whole number part
return retVal
它的使用方式如下:
>>> get_pos_float(1.23, 10)
2
>>> get_pos_float(1.23, 100)
3
你是否正在寻找int()
:
In [39]: a = 1.23
In [40]: int(a)
Out[40]: 1
In [41]: a
Out[41]: 1.23
- g4ur4va-int(a) 0.22999999999999998,它四舍五入为0.23
你不能像索引一个集合一样索引浮点数。关于浮点数的工作原理,可以阅读http://docs.oracle.com/cd/E19957-01/806-3568/ncg_goldberg.html获取更多信息。
数学库提供了一种获取该数字两个部分元组的方法。
>>> import math
>>> a = 1.23
>>> math.modf(a)
(0.22999999999999998, 1.0)
这并不准确,因为浮点数的表示方式,但是值大约在1e-17的数量级。
当然,这也是可能的...
>>> map(int, str(a).split('.'))
[1, 23]