假设以下数字:
local a = 2
local b = 3.1
local c = 1.43
local d = 1.0582
Run Code Online (Sandbox Code Playgroud)
我的目标是将这些数字四舍五入到小数点后两位。结果应该分别是这样的:
a = 2.00
b = 3.10
c = 1.43
d = 1.06 or 1.05
Run Code Online (Sandbox Code Playgroud)
显然,我知道任何带有尾随小数零的数字都会被四舍五入。2.00
将2
。但我需要将数字作为字符串,并且为了使其在视觉上更具吸引力,我需要这两个小数位。
这是我用来四舍五入到小数点后两位的函数:
function round(num, numDecimalPlaces)
local mult = 10^(numDecimalPlaces or 0)
return math.floor(num * mult + 0.5) / mult
end
Run Code Online (Sandbox Code Playgroud)
这对于测试用例c
和效果很好d
,但会产生错误的结果 和a
:b
它不会用零填充。我理解这是因为舍入函数获取数字并计算它们 - 因此多余的零被切断。
但这并不是我的目标——不是切断它们。
我尝试过字符串操作,通过检查 a 是否在数字中以及在数字中的位置,但这在任何情况下都.
不起作用。我的方法:
local zei
if i < 100 then
if tostring(i):find("%.") == nil then
zei = round(i, 2) .. ".00" --No decimal point found, append .00
else
zei = round(i, 2) --Found decimal point, round to 2
end
if tostring(i):find("%.")+2 == tostring(i):len() then
zei = round(i, 2) .. "0" --Found point, but only one trailing number, append 0
end
else
zei = round(i, 0) --Number is over 100, no decimal points needed
end
Run Code Online (Sandbox Code Playgroud)
上面的100
例子只是为了美观,与这里无关。其中zei
是显示的字符串,i
是测试用例编号之一。
我如何将数字四舍五入到小数点后两位,但附加尾随零,即使它们是多余的,例如2.30
?我知道我需要字符串。
你不对数字进行四舍五入。您创建这些数字的字符串表示形式。这将由 完成string.format
,并采用适当的格式。像这样:
string.format("%.2f", a);
Run Code Online (Sandbox Code Playgroud)