JavaScript格式化数字

格式化数字:小数点前每三位添加逗号,小数点后不改变

介绍两种常用的格式化数字的方法:

  • 字符串方法
  • 字符串replace+正则表达式
    	function toThousands0(item){
    		var item0=item.toString();
    		var dot="";
    		if (item0.indexOf(".")!=-1) {
    			dot=item0.slice(item0.indexOf("."));//保留小数点后的内容
    			item0=item0.slice(0,item0.indexOf("."));
    		}
    		var res='';
    		while(item0.length>3){
    			res=","+item0.slice(-3)+res;
    			item0=item0.slice(0,item0.length-3);
    		}
    		if (item0) {
    			res=item0+res;
    		}
    		return res+dot;

    	}
    	console.log(toThousands0(22.12578));
    	console.log(toThousands0(7777.0123));
        console.log(toThousands0(10));

运行结果:

		function toThousands1(num) {
			 var item0=num.toString();
			 var res="";
			 var dot="";
    		 if (item0.indexOf(".")!=-1) {
    			dot=item0.slice(item0.indexOf("."));
    			item0=item0.slice(0,item0.indexOf("."));
    		}
		      res= item0.replace(/(\d)(?=(\d{3})+$)/g, "$1,");
		      return res+dot;
		 }
		 console.log(toThousands1(12345678901.10));
         console.log(toThousands1(123.5));

运行结果:

详解:

  1. \d表示匹配数字
  2. ()表示分组,分组一般和$1 $2...一起使用表示匹配的第一个分组第二个分组JavaScript正则表达式之分组匹配 / 反向引用
  3. 量词:{m}m次,{m,n}大于等于m小于等于n,{m,}表示大于等于m次,?={0,1},+={1,}
  4. ^开头$结尾
  5. g global全局匹配 i ignorCase忽略大小写 m mutiple允许多行匹配
  6. replace第二个参数使用$必须加引号
  7. 有关?=的含义:

(?=)和(?!);零宽正向断言和负向断言,括号内表示某个位置右边必须和=右边匹配上,或者不和!后的字符匹配。

exp1(?=exp2) 查找exp2前面的exp1

exp1(?!exp2) 查找后面不是exp2的exp1

var pattern=/str(?=ings)ing/; 
console.log("strings.a".match(pattern)); 
console.log("strings.a".match(/string(?=s)/));
console.log("string_x".match(pattern));
console.log("string_x".match(/string(?=s)/)); 

注:

  • 这里一定要用到分组()还有全局匹配g,类似一个遍历的过程。
  • 如果有负号的话,建议像处理dot一样处理一下即可。

正则表达式的另外应用:字符串前面后面去空格:

const TRIM_REGX = /(^\s+)|(\s+$)/g;//因为是去首尾空格所以一定需要^和$,注意是多个空格所以一定要用+,表示出现1次及一次以上≥1,也就是{1,}  |表示或操作符
var myres0=' ScriptOJ   '.replace(TRIM_REGX, '') // => ScriptOJ
console.log(myres0.length);

 

 

运行结果:

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值