js中阿拉伯数字改为一二三、十一十二等中文小写

由于需求为 xxx一、xxxx二的展示

但只能有index+1得到 1、2、3 所以 写了一个js进行转换

痛点:当数字超过10之后 普通的转换 只能转换为一零

解决方法:

1、创建一个js文件 专门用来写转换的方法 并暴露出去

// 判断方法 mixin
export default {
    methods: {
        numberChinese(number) {
            var units = '个十百千万@#%亿^&~', chars = '零一二三四五六七八九';
            var a = (number + '').split(''), s = []
            if (a.length > 12) {
                throw new Error('too big');
            } else {
                for (var i = 0, j = a.length - 1; i <= j; i++) {
                    if (j == 1 || j == 5 || j == 9) {//两位数 处理特殊的 1*
                        if (i == 0) {
                            if (a[i] != '1') s.push(chars.charAt(a[i]));
                        } else {
                            s.push(chars.charAt(a[i]));
                        }
                    } else {
                        s.push(chars.charAt(a[i]));
                    }
                    if (i != j) {
                        s.push(units.charAt(j - i));
                    }
                }
            }
            //return s;
            return s.join('').replace(/零([十百千万亿@#%^&~])/g, function (m, d, b) {//优先处理 零百 零千 等
                b = units.indexOf(d);
                if (b != -1) {
                    if (d == '亿') return d;
                    if (d == '万') return d;
                    if (a[j - b] == '0') return '零'
                }
                return '';
            }).replace(/零+/g, '零').replace(/零([万亿])/g, function (m, b) {// 零百 零千处理后 可能出现 零零相连的 再处理结尾为零的
                return b;
            }).replace(/亿[万千百]/g, '亿').replace(/[零]$/, '').replace(/[@#%^&~]/g, function (m) {
                return { '@': '十', '#': '百', '%': '千', '^': '十', '&': '百', '~': '千' }[m];
            }).replace(/([亿万])([一-九])/g, function (m, d, b, c) {
                c = units.indexOf(d);
                if (c != -1) {
                    if (a[j - c] == '0') return d + '零' + b
                }
                return m;
            });
        }

    }
}

2、在对应的vue文件中进行引用

<script>
import numberChiness from './numberChiness.js'

export default {
  name: '',
  mixins: [numberChiness],

  data() {
    return {}
  },
  props: {
    form: Object,
  },
  components: {},
  computed: {},
  created() {},
  mounted() {},
  methods: {},
}
</script>

3、使用:

numberChinese(index + 1)

大功告成!!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值