Lua 格式化数字 (每三位加逗号)
function GameUtil.formatNum( numTmp )
local resultNum = numTmp
if type(numTmp) == "number" then
local inter, point = math.modf(numTmp)
local strNum = tostring(inter)
local newStr = ""
local numLen = string.len( strNum )
local count = 0
for i = numLen, 1, -1 do
if count % 3 == 0 and count ~= 0 then
newStr = string.format("%s,%s",string.sub( strNum,i,i),newStr)
else
newStr = string.format("%s%s",string.sub( strNum,i,i),newStr)
end
count = count + 1
end
if point > 0 then
--@desc 存在小数点,
local strPoint = string.format( "%.2f", point )
resultNum = string.format("%s%s",newStr,string.sub( strPoint,2, string.len( strPoint )))
else
resultNum = newStr
end
end
return resultNum
end
思路:首先为有效的数字,其次分离整数、小数部分,整数部分三位拼一个逗号,最后拼接小数部分。
网友评论