lua 实现数字转换千分法描述的字符串
作者:互联网
话不多说,直接上代码。
-- 如 1234567 转换为 1,234,567
---@param number 数字
---@param decimalCount 需要保留小数点后的位数
function thousandNum(number, decimalCount)
if type(number) ~= "number" then
return number;
end
if number == math.huge then
return tostring(number);
end
local intNum = number;
local floatStr = "";
--如果是小数,需要保留小数点后的数字
local arr = stringExplode(tostring(number), ".");
if Utils.sizeof(arr) > 1 then
intNum = tonumber(arr[1]); --整数部分
floatStr = arr[2]; --小数部分
end
if decimalCount and decimalCount > 0 then
floatStr = string.sub(floatStr, 1, decimalCount);
if sizeof(floatStr) < decimalCount then
-- 小数部位位数不足的,用0补足
for i = 1, decimalCount - sizeof(floatStr) do
floatStr = floatStr .. "0" ;
end
end
end
local ret;
repeat
local num , _ = math.modf(intNum % 1000);
intNum = (intNum - num) / 1000;
local str = tostring(num)
if intNum <= 0 then
str = tostring(num);
end
if ret then
ret = str .. "," .. ret;
else
ret = str;
end
until intNum <= 0;
if Utils.sizeof(floatStr) > 0 then
ret = string.format("%s.%s", ret, floatStr);
end
return ret;
end
---@param t table or string
function sizeof(t)
local n = 0;
if type(t) == "table" then
-- 遍历 table,累加元素个数
for __, __ in pairs(t) do
n = n + 1;
end
elseif type(t) == "string" then
n = string.len(t);
end
return n;
end
-- 将字符串打断
function stringExplode(str, sep)
if sep == nil then
sep = "%s"
end
local t = {};
local i = 1;
for str in string.gmatch(str, "([^"..sep.."]+)") do
t[i] = str;
i = i + 1;
end
return t;
end
标签:end,floatStr,--,千分,number,lua,decimalCount,字符串,local 来源: https://blog.csdn.net/qq_37659181/article/details/114896957