Lua 格式化返回意想不到的结果

问题描述 投票:0回答:1

我最近编写了一个小程序,我试图将秒数转换为更人类可读的格式,但在尝试格式化输出时遇到问题,不知何故我最终得到了意外的输出。这是代码

local minutes, hours = 60, 3600
local s = 5400

-- output is 2h30m when it should be 1h30m
if s >= hours then
    print(string.format("%.0fh%.0fm", s / hours, (s % hours) / minutes))
end

-- output is 45m0s when it should be 45m
if s >= minutes then
    print(string.format("%.0fm%.0fs", s / minutes, s % minutes))
end

即使秒数为 5400,即 1 小时 30 分钟,第一个

if
语句将输出 2h30m,即多一个小时,而第二个
if
语句则打印正确的 90m。如果你们能帮助我提供一些想法或为我指明正确的方向,我将不胜感激!祝你玩得开心!

string lua formatting string-formatting
1个回答
0
投票

问题源于

%.0f
不会截断:它会四舍五入。
print(("%.0f"):format(1.5))
打印
2
,而不是
1
。这里的情况正是如此:您有 1h30m,或 1.5h(“边缘情况”)。这会被
%.0f
四舍五入到两个小时。你真正想要的是楼层划分。只需将除法包裹在
math.floor
中即可;那么您也可以使用
%d
进行整数格式化:

print(string.format("%dh%dm", math.floor(s / hours), math.floor((s % hours) / minutes))) -- 1h30m as expected
© www.soinside.com 2019 - 2024. All rights reserved.