如何截断数字?

时间:2015-08-18 09:13:20

标签: python

我有数字,例如:

100.1264
9.09
123
1298.456789

我希望将其截断为:

100.12
9.09
123
1298.45

如何截断这些数字以便保留其形式?

2 个答案:

答案 0 :(得分:1)

如果你有数字(不是字符串),你可以使用:

import math
math.trunc(x * 100) / 100

例如:

>>> import math
>>> x = 100.1264
>>> math.trunc(x * 100) / 100
100.12

您也可以使用int代替math.trunc,但要注意浮点数和整数之间的转换可能在计算上很昂贵。

额外提示:如果您想要任意精确十进制算术,请查看decimal module

答案 1 :(得分:0)

s="""100.1264
9.09
123
343.1
1298.456789"""
print re.sub(r"(?<=\.)(\d{2})\d+",r"\1",s)

如果您的输入是浮点数,则可以使用

s=100.1264

print ast.literal_eval(re.sub(r"(?<=\.)(\d{2})\d+",r"\1",str(s)))
相关问题