首页 > 建站教程 > JS、jQ、TS >  js将数字转为中文正文

js将数字转为中文

    我爱模板网在做今日周边项目时,有个拉黑的功能,拉黑时长是后台设置的,返回的是数字,如:1,2,3。但是展示的时候,需要展示为:拉黑此商家一天,也就是数字必须转为中文,使用下面的方法,可以很好解决这个问题:
let toChinesNum = (num) => {
    let changeNum = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九']; 
    let unit = ["", "十", "百", "千", "万"];
    num = parseInt(num);
    let getWan = (temp) => {
      let strArr = temp.toString().split("").reverse();
      let newNum = "";
      for (var i = 0; i < strArr.length; i++) {
        newNum = (i == 0 && strArr[i] == 0 ? "" : (i > 0 && strArr[i] == 0 && strArr[i - 1] == 0 ? "" : changeNum[strArr[i]] + (strArr[i] == 0 ? unit[0] : unit[i]))) + newNum;
      }
       return newNum;
   }
   let overWan = Math.floor(num / 10000);
   let noWan = num % 10000;
   if (noWan.toString().length < 4) {
      noWan = "0" + noWan;
    }
   return overWan ? getWan(overWan) + "万" + getWan(noWan) : getWan(num);
}
    使用示例:
console.log(toChinesNum(123));
console.log(toChinesNum(12));
console.log(toChinesNum(32));
    控制台打印结果:

js将数字转为中文