Lua 格式化數(shù)字 (每三位加逗號(hào))
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 存在小數(shù)點(diǎn)捅僵,
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
思路:首先為有效的數(shù)字慷妙,其次分離整數(shù)眷昆、小數(shù)部分演训,整數(shù)部分三位拼一個(gè)逗號(hào)弟孟,最后拼接小數(shù)部分。