Skip to main content
 首页 » 编程设计

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

2025年05月04日1798°冷暖

这是我的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 的次数),以及剩余的秒数。对分钟数再次应用相同的函数,您将得到小时和分钟的余数。