字符串中插入千位分隔符/整数千分位加逗号:

文章目录

          • 1、 正则表达式实现
          • 2、效果
          • 3、普通方法实现


1、 正则表达式实现
function thousandSign2(num) {
  return (num+"").replace(/\d(?=(\d{3})+$)/g, "$&,")
}
console.log(thousandSign2(1589470000)) // 1,589,470,000

使用案例:(vue和uniapp)

methods: {
	// 正则表达式实现
	thousandSign2(num) {
		return (num+"").replace(/\d(?=(\d{3})+$)/g, "$&,")
	},
	// 获取列表数据
	async myContract() {
		this.questFun('contract/ownList', 'post', 'bd', this.argInfo, (data) => {
			if (data.data.code == 0) {
				this.ContractList = data.data.data.list;
				//遍历数据,给需要的数据添加千位分隔符
				this.ContractList.forEach((item,index)=>{
					item.money=this.thousandSign2(item.money)
				})
			} else if (data.data.code === 501) {
				this.toLogin(data.data.msg);
			} else {
				uni.showToast({
					title: data.data.msg,
					icon: 'none'
				})
			}
		})
   },
 }
2、效果

字符串中插入千位分隔符/整数千分位加逗号:_第1张图片

3、普通方法实现
function toThousands(num) {
    num = num.toString()
    let result = ''
    while (num.length > 3) {
        result = ',' + num.substring(num.length - 3) + result
        num = num.substring(0, num.length - 3)
    }
    result = num + result
    return result
}
console.log(toThousands(1234567)) // 1,234,567
console.log(toThousands(123456)) // 123,456

你可能感兴趣的:(JavaScript,vue.js,前端,javascript)