Python中能否将函数返回的float类型转换为integer类型?
如何将Python中分钟/秒转小时的float结果转为integer类型?
当然可行啦!根据你想要的不同效果,这里有几种实用的处理方法,你可以按需选择:
方法1:直接截断小数部分转为整数
如果你的需求是只保留小时的整数部分(比如1.666...直接变成1,1.0变成1),可以直接用Python内置的int()函数转换结果。修改后的代码如下:
def minutes_to_hours(minutes): hours = minutes / 60 return int(hours) def seconds_to_hours(seconds): hours = seconds / 3600 return int(hours) print(minutes_to_hours(100)) # 输出: 1 print(seconds_to_hours(3600)) # 输出: 1
注意:int()会直接去掉小数部分,不会做四舍五入哦。
方法2:四舍五入到最近整数
如果你希望对结果进行四舍五入(比如1.666...变成2,1.0保持1),可以使用round()函数:
def minutes_to_hours(minutes): hours = minutes / 60 return round(hours) def seconds_to_hours(seconds): hours = seconds / 3600 return round(hours) print(minutes_to_hours(100)) # 输出: 2 print(seconds_to_hours(3600)) # 输出: 1
方法3:仅转换整数型float为int,保留非整数结果
如果你的需求是只把刚好是整数的float(比如1.0)转成int,而像1.666...这样的非整数结果仍保留float类型,可以用is_integer()方法判断后再转换:
def minutes_to_hours(minutes): hours = minutes / 60 return int(hours) if hours.is_integer() else hours def seconds_to_hours(seconds): hours = seconds / 3600 return int(hours) if hours.is_integer() else hours print(minutes_to_hours(100)) # 输出: 1.6666666666666667 print(seconds_to_hours(3600)) # 输出: 1
你可以根据自己的实际需求挑选对应的方法~
内容的提问来源于stack exchange,提问作者Arpan Sharma




