const numberToChinese = (num) => { if (typeof num !== "number") { throw new Error("function only accept number type"); } const nums = num .toString() .replace(/(?=(\d{4})+$)/g, ",") .split(",") .filter(Boolean);
const chineseMap = ["", "万", "亿"]; let res = ""; for (let i = 0; i < nums.length; i++) { const chinese = conversion(nums[i]); const unit = chineseMap[nums.length - i - 1]; if (chinese === "") { res += "零"; continue; } res += chinese + unit; } res = handlerZero(res); return res; };
const conversion = (n) => { const chineseMap = [ "零", "一", "二", "三", "四", "五", "六", "七", "八", "九", ]; const unit = ["", "十", "百", "千"]; let res = ""; for (let i = 0; i < n.length; i++) { const digit = chineseMap[n[i]]; let u = unit[n.length - i - 1]; if (digit === "零") { u = ""; } res += digit + u; } res = handlerZero(res); return res; };
const handlerZero = (str) => str.replace(/零+/g, "零").replace(/零$/, "");
console.log(numberToChinese(1200008998));
|