js万亿级数字转汉字的封装方法

要求如图:

实现方法:

function changeBillionToCN(c) {
                //                对传参进行类型处理,非字符串进行转换
                if(typeof(c) != "string") {
                    c = c.toString();
                }
                //                对参数进行判断,
                if(c.split(".")[0].length >= 3 && c.split(".")[0].length < 4) {
                    return(c / 1000).toFixed(2) + "千";
                } else if(c.split(".")[0].length >= 4 && c.split(".")[0].length < 8) {
                    return(c / 10000).toFixed(2) + "万";
                } else if(c.split(".")[0].length >= 8 && c.split(".")[0].length < 13) {
                    return(c / 100000000).toFixed(2) + "亿";
                } else if(c.split(".")[0].length >= 13) {
                    return(c / 1000000000000).toFixed(2) + "兆";
                }
            }

实测结果:

知识点:

1.数字对字符串的转换:number.toString();

2.字符串长度的判断:string.length;

3.字符串的切割与拼接:string.split(" ")【引号标住需要切开的点】

4.与非或:&&   ||   !

5.小数取位:string.toFixed(2)【括号2代表取2位有效小数】

原文地址:https://www.cnblogs.com/chig/p/8422539.html