Lua格式化输出异常求助:秒转可读时间格式结果不符
问题分析与修复方案
第一个问题:小时数被四舍五入导致错误
你代码里用%.0fh格式化小时数时,这个格式会对数值四舍五入。5400秒除以3600等于1.5,四舍五入后变成2,所以输出了错误的2h30m。
解决方法:用整数除法获取小时的整数部分,比如Lua的math.floor()函数,或者5.3及以上版本支持的//整除运算符。
第二个问题:多余的0秒输出
当秒数刚好是分钟的整数倍时,s % minutes结果为0,固定格式会强制输出0s。需要动态判断,只有当秒数余数不为0时才添加秒的部分。
修复后的完整代码
local minutes, hours = 60, 3600 local s = 5400 -- 修复后输出1h30m if s >= hours then local h = math.floor(s / hours) local m = math.floor((s % hours) / minutes) print(string.format("%dh%dm", h, m)) end -- 修复后:当s=2700(45分钟)时输出45m,而非45m0s s = 2700 if s >= minutes then local m = math.floor(s / minutes) local sec = s % minutes local output = string.format("%dm", m) if sec > 0 then output = output .. string.format("%ds", sec) end print(output) end
通用优化方案(自动适配最简格式)
如果想要让程序自动根据秒数生成最简洁的格式(比如不足一分钟只显示秒,不足一小时只显示分秒),可以整合逻辑:
local minutes, hours = 60, 3600 local s = 5400 local h = math.floor(s / hours) local m = math.floor((s % hours) / minutes) local sec = s % minutes local parts = {} if h > 0 then table.insert(parts, string.format("%dh", h)) end if m > 0 then table.insert(parts, string.format("%dm", m)) end if sec > 0 or #parts == 0 then -- 无更高单位时强制显示秒 table.insert(parts, string.format("%ds", sec)) end print(table.concat(parts))
这个版本的输出会自动适配:
- 5400 →
1h30m - 2700 →
45m - 65 →
1m5s - 40 →
40s
内容的提问来源于stack exchange,提问作者Jerry Jones
相关产品推荐
相关产品推荐

