数字转中文
-
传入万亿以下的整数转中文
/** * 数字转中文 * @param {number} number 万亿以下的数字 */ function transformToChineseNumber(number) { // number 每四位四位分割 const num = number.toString().replace(/(?=(\d{4})+$)/g, ","); // num 按,分割 const arr = num.split(",").filter(Boolean); // console.log(arr); const _number_map = { 0: "零", 1: "一", 2: "二", 3: "三", 4: "四", 5: "五", 6: "六", 7: "七", 8: "八", 9: "九", }; const _unit_map = ["", "十", "百", "千"]; const _big_unit_map = ["", "万", "亿"]; /** * 处理传入的字符串中的数字 * @param {string} _number_string 待处理字符串数字 */ function _handleZero(_number_string) { return _number_string.replace(/零+/g, "零").replace(/零$/, ""); } /** * 转换四位数字 * */ function _transformNumber4(_num) { let _res = ""; for (let i = 0; i < _num.length; i++) { const _res_num = _number_map[_num[i]]; let _res_unit = _unit_map[_num.length - 1 - i]; if (_res_num == "零") { _res_unit = ""; } _res += _res_num + _res_unit; } _res = _handleZero(_res); return _res; } let res = ""; for (let i = 0; i < arr.length; i++) { const c = _transformNumber4(arr[i]); const _big_unit = _big_unit_map[arr.length - i - 1]; // console.debug("c = ", c, " _big_unit = ", _big_unit); res += c + _big_unit; } return res; }
评论区