阿拉伯数字转换为简写汉字

/*
  *阿拉伯数字转换为简写汉字
*/
export const toolsNumToCN = (Num) => {
  if (Num == null) {
    return ''
  }
  for (let i = Num.length - 1; i >= 0; i--) {
    Num = Num.replace(',', '')// 替换Num中的“,”
    Num = Num.replace(' ', '')// 替换Num中的空格
  }
  if (isNaN(Num)) { // 验证输入的字符是否为数字
    // alert("请检查小写金额是否正确");
    return
  }
  // 字符处理完毕后开始转换,采用前后两部分分别转换
  const part = String(Num).split('.')
  let newChar = ''
  // 小数点前进行转化
  for (let i = part[0].length - 1; i >= 0; i--) {
    if (part[0].length > 10) {
      // alert("位数过大,无法计算");
      return ''
    }// 若数量超过拾亿单位,提示
    let tmpNewChar = ''
    const partChar = part[0].charAt(i)
    switch (partChar) {
      case '0': tmpNewChar = '零' + tmpNewChar; break
      case '1': tmpNewChar = '一' + tmpNewChar; break
      case '2': tmpNewChar = '二' + tmpNewChar; break
      case '3': tmpNewChar = '三' + tmpNewChar; break
      case '4': tmpNewChar = '四' + tmpNewChar; break
      case '5': tmpNewChar = '五' + tmpNewChar; break
      case '6': tmpNewChar = '六' + tmpNewChar; break
      case '7': tmpNewChar = '七' + tmpNewChar; break
      case '8': tmpNewChar = '八' + tmpNewChar; break
      case '9': tmpNewChar = '九' + tmpNewChar; break
    }
    switch (part[0].length - i - 1) {
      case 0: tmpNewChar = tmpNewChar; break
      case 1: if (partChar !== '0') tmpNewChar = tmpNewChar + '十'; break
      case 2: if (partChar !== '0') tmpNewChar = tmpNewChar + '百'; break
      case 3: if (partChar !== '0') tmpNewChar = tmpNewChar + '千'; break
      case 4: tmpNewChar = tmpNewChar + '万'; break
      case 5: if (partChar !== '0') tmpNewChar = tmpNewChar + '十'; break
      case 6: if (partChar !== '0') tmpNewChar = tmpNewChar + '百'; break
      case 7: if (partChar !== '0') tmpNewChar = tmpNewChar + '千'; break
      case 8: tmpNewChar = tmpNewChar + '亿'; break
      case 9: tmpNewChar = tmpNewChar + '十'; break
    }
    newChar = tmpNewChar + newChar
  }
  // 替换所有无用汉字,直到没有此类无用的数字为止
  while (newChar.search('零零') !== -1 || newChar.search('零亿') !== -1 || newChar.search('亿万') !== -1 || newChar.search('零万') !== -1) {
    newChar = newChar.replace('零亿', '亿')
    newChar = newChar.replace('亿万', '亿')
    newChar = newChar.replace('零万', '万')
    newChar = newChar.replace('零零', '零')
  }
  // 替换以“一十”开头的,为“十”
  if (newChar.indexOf('一十') === 0) {
    newChar = newChar.substr(1)
  }
  // 替换以“零”结尾的,为“”
  if (newChar.lastIndexOf('零') === newChar.length - 1) {
    newChar = newChar.substr(0, newChar.length - 1)
  }
  return newChar
}

你可能感兴趣的:(阿拉伯数字转换为简写汉字)