本文介绍了在 Lua 中格式化整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想将数字格式化为 1,234 或 1,234,432 或 123,456,789,你懂的.我尝试这样做:
I'd like to format a number to look like 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, a failed attempt, my problem is that I can't figure out what the error is because the program I am running this in refuses to report an 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 中格式化整数
发布评论