在Lua中格式化整数

编程入门 行业动态 更新时间:2024-10-23 19:28:22
本文介绍了在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中格式化整数

本文发布于:2023-05-28 12:29:45,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/320918.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:整数   Lua

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!