移动小数而不舍入

时间:2015-12-18 20:43:47

标签: python

我使用.get_seconds()函数减去时间并将日期时间转换为字符串。

diff = end_date - start_date
seconds = diff.total_seconds()
months = seconds / 2628000
years = months / 12

当我打印years时,号码会显示为0.830136986301

我在查看Python中的格式化选项

format(years, '.0f')

但是这会将其四舍五入到1。无论如何我只能" cut"没有它四舍五入的小数点?

5 个答案:

答案 0 :(得分:1)

无论如何,我可以在没有四舍五入的情况下“减少”小数点吗?

根据定义,不可能,因为“减少小数点数”意味着向下舍入。所以,不,你不能。但是,您可以操纵数字舍入的方式!

根据我对您的问题的理解,您可以转换为int以获得所需的结果(这类似于四舍五入),如下所示:

>>>print(int(years))
0

答案 1 :(得分:1)

您需要的是整数除法,它以“//”执行。

#And then 
years // 12 # Will give you integer without the decimals.

答案 2 :(得分:1)

这个解决方案有点使用舍入,但你可以说:

years = math.floor(months / 12)

但更好的是,您可以通过说:

来截断该值
years = math.trunc(months / 12)

我个人更喜欢截断地板,因为截断和地板处理负值的方式不同。但是,在您的情况下,假设值始终为正,则两者都应该是产生相同结果的合适解决方案。此外,它们都依赖math模块,因此您需要在脚本的顶部加入import math

答案 3 :(得分:1)

如果您的号码可以是负面的,请注意楼层功能。以下是各种float到int转换函数的比较

list(map(math.floor, (0.734, -0.734, 0.314, -0.314)))
[0, -1, 0, -1]

list(map(math.ceil, (0.734, -0.734, 0.314, -0.314)))
[1, 0, 1, 0]

list(map(int, (0.734, -0.734, 0.314, -0.314)))
[0, 0, 0, 0]

list(map(round, (0.734, -0.734, 0.314, -0.314)))
[1, -1, 0, 0]

list(map(math.trunc, (0.734, -0.734, 0.314, -0.314)))
[0, 0, 0, 0]

答案 4 :(得分:0)

这有效:

format(math.floor(number), '.0f')