function formatNumberToChinese(num)
local chineseNum = {"零", "一", "二", "三", "四", "五", "六", "七", "八", "九"}
local units = {"", "十", "百", "千", "万"}
if num == 0 then
return chineseNum[1]
end
local result = ""
local unitIndex = 1
local lastNonZero = false -- 用于标记前一位是否为非零数字
while num > 0 do
local digit = num % 10
if digit ~= 0 then
result = chineseNum[digit + 1] .. units[unitIndex] .. result
lastNonZero = true
elseif lastNonZero then
result = chineseNum[digit + 1] .. result -- 添加单位,但不添加零
lastNonZero = false
end
unitIndex = unitIndex + 1
num = math.floor(num / 10)
end
-- 处理特殊情况:当结果以"一十"开头时,去除前面的"一"
if string.sub(result, 1, 6) == "一十" then
result = string.sub(result, 4)
end
return result
end
Lua 数字换算中文数字
于 2024-03-11 15:09:20 首次发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)