python - 如何在 'int' 函数中将数字四舍五入到十分之一?

标签 python python-2.7 int rounding

这是我的convert_seconds 函数:

def convert_seconds(x):
    hour = int(round(x / 3600))
    minute = int(round(x / 60 - hour * 60))
    second = int(round(x - (hour * 3600 + minute * 60), 1))
    return str(hour) + ' hours, ' + str(minute) + ' minutes, ' + str(second) +' seconds'

当我运行我的函数时:

>>>print convert_seconds(7261.7)
2 hours, 1 minute, 1 seconds

它打印出“1 秒”而不是“1.7 秒”

这是为什么呢? 我该如何解决?

注意:我需要的输出是:

>>>print convert_seconds(7261.7)
2 hours, 1 minute, 1.7 seconds

谢谢。

最佳答案

Why is that?

因为您明确地将结果转换为整数,删除了小数点后的任何内容:

second = int(round(x - (hour * 3600 + minute * 60), 1))

How can I fix that?

不要将 seconds 结果变成整数:

second = round(x - (hour * 3600 + minute * 60), 1)

您不应该四舍五入小时分钟计算;您应该代替结果; int() 本身就可以为您做到这一点。删除对这两个值的 round() 调用。 // floor 除法运算符会为您提供与对除法结果调用 int() 相同的结果,从而无需显式舍入或 floor。

您可以使用格式化操作将值仅显示为小数:

>>> def convert_seconds(x):
...     hour = x // 3600
...     minute = x // 60 - hour * 60
...     second = x - (hour * 3600 + minute * 60)
...     return '{:.0f} hours, {:.0f} minutes, {:.1f} seconds'.format(hour, minute, second)
... 
>>> convert_seconds(7261.7)
'2 hours, 1 minutes, 1.7 seconds'

要将浮点值四舍五入为小数点后一位,但删除.0(如果这是四舍五入的结果),您需要显式地将.0:

>>> def convert_seconds(x):
...     hour = x // 3600
...     minute = x // 60 - hour * 60
...     second = x - (hour * 3600 + minute * 60)
...     second_formatted = format(second, '.1f').rstrip('0').rstrip('.')
...     return '{:.0f} hours, {:.0f} minutes, {} seconds'.format(hour, minute, second_formatted)
... 
>>> convert_seconds(7261.7)
'2 hours, 1 minutes, 1.7 seconds'
>>> convert_seconds(7261)
'2 hours, 1 minutes, 1 seconds'

表达式 format(second, '.1f').rstrip('0').rstrip('.') 格式化 seconds 值但删除任何 .0 首先剥离 0 然后剥离剩余的 ..

您可能想要使用 divmod() function 而不是除法和减法:

def convert_seconds(x):
    minutes, seconds = divmod(x, 60)
    hours, minutes = divmod(minutes, 60)
    second_formatted = format(seconds, '.1f').rstrip('0').rstrip('.')
    return '{:.0f} hours, {:.0f} minutes, {} seconds'.format(hours, minutes, second_formatted)

divmod() 函数返回商 余数的结果; divmod(x, 60) 返回分钟数(x 中 60 的次数),以及剩余的秒数。对分钟数再次应用相同的函数,您将得到小时和分钟的余数。

关于python - 如何在 'int' 函数中将数字四舍五入到十分之一?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18804301/

相关文章:

python-2.7 - 人脸识别中预测未知面孔

python - Flower 中的高级任务格式化(Celery 监控)

python - Pandas 一次将多列的 datetime64 [ns] 列转换为 datetime64 [ns, UTC]

python - 使用单词列表的正则表达式

python - ubyte_scalars 遇到运行时警告溢出

c++ - 将 int 转换为 char。没有存储正确的值

python - `.0`中不可访问的 `locals()`变量是否影响内存或性能?

python - 在 Python 中写入和读取相同的 csv 文件

c# - 在 C# 中将字符串/整数转换为 double

c++ - c++ 中有标准的 'int class' 吗?