Lua - 格式整数 [英] Lua - Format integer
本文介绍了Lua - 格式整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想格式化一个数字看起来如下1,234或1,234,432或123,456,789,你明白了。我尝试这样做如下;
i'd like to format a number to look as follows "1,234" or "1,234,432" or "123,456,789", you get the idea. I tried doing this as follows;
function reformatint(i)
local length = string.len(i)
for v = 1, math.floor(length/3) do
for k = 1, 3 do
newint = string.sub(mystring, -k*v)
end
newint = ','..newint
end
return newint
end
正如你所看到我尝试失败,问题是我无法弄清楚我正在运行的程序有什么问题,拒绝向我发回错误。
As you can see I have a failed attempt, problem is I cannot work out what's at fault as the program i am running this in, refuses to post a error back to me.
推荐答案
这是一个将负数和小数部分考虑在内的函数:
Here's a function that takes negative numbers, and fractional parts into account:
function format_int(number)
local i, j, minus, int, fraction = tostring(number):find('([-]?)(%d+)([.]?%d*)')
-- reverse the int-string and append a comma to all blocks of 3 digits
int = int:reverse():gsub("(%d%d%d)", "%1,")
-- reverse the int-string back remove an optional comma and put the
-- optional minus and fractional part back
return minus .. int:reverse():gsub("^,", "") .. fraction
end
assert(format_int(1234) == '1,234')
assert(format_int(1234567) == '1,234,567')
assert(format_int(123456789) == '123,456,789')
assert(format_int(123456789.1234) == '123,456,789.1234')
assert(format_int(-123456789.) == '-123,456,789')
assert(format_int(-123456789.1234) == '-123,456,789.1234')
assert(format_int('-123456789.1234') == '-123,456,789.1234')
print('All tests passed!')
这篇关于Lua - 格式整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文