vue中使用js实现千分位分割-函数封装

vue过滤器中使用 

filters: {
	//第一种
    Statistic(num) {
	  let [integer, decimal] = String.prototype.split.call(num, '.')
	  integer = (integer || 0).toString()
	  let result = ''
	  while (integer.length > 3) {
		result = ',' + integer.slice(-3) + result
		integer = integer.slice(0, integer.length - 3)
	  }
	  if (integer) {
		result = integer + result
	  }
	  return `${result}${decimal ? '.' + decimal : ''}`
	},
    //第二种
	Statistic1(num) {
	  num = parseFloat(Number(num).toFixed(3))
	  let [integer, decimal] = String.prototype.split.call(num, '.')
	  integer = integer.replace(/\d(?=(\d{3})+$)/g, '$&,') // 正则先行断言
	  return `${integer}${decimal ? '.' + decimal : ''}`
	},
    //第三种
    let thousandth = (s, type = 0) => {
	  // if (!s) return '0';
	  // return (s+'').replace(/(\d{1,3})(?=(\d{3})+(?:$|\.))/g,'$1,');

	  if (/[^0-9\.]/.test(s)) return "0";
	  if (s == null || s == "") return "0";
	  s = s.toString().replace(/^(\d*)$/, "$1.");
	  s = (s + "00").replace(/(\d*\.\d\d)\d*/, "$1");
	  s = s.replace(".", ",");
	  var re = /(\d)(\d{3},)/;
	  while (re.test(s)) s = s.replace(re, "$1,$2");
	  s = s.replace(/,(\d\d)$/, ".$1");
	  if (type == 0) {
		// 不带小数位(默认是有小数位)
		var a = s.split(".");
		if (a[1] == "00") {
		  s = a[0];
		}
	  }
	  return s;
	}
}

js函数

第一种
function toThousands(num) {
  let [integer, decimal] = String.prototype.split.call(num, '.')
  integer = (integer || 0).toString()
  let result = ''
  while (integer.length > 3) {
	result = ',' + integer.slice(-3) + result
	integer = integer.slice(0, integer.length - 3)
  }
  if (integer) {
	result = integer + result
  }
  return `${result}${decimal ? '.' + decimal : ''}`
},
第二种
function toThousands(num) {
  num = parseFloat(Number(num).toFixed(3))
  let [integer, decimal] = String.prototype.split.call(num, '.')
  integer = integer.replace(/\d(?=(\d{3})+$)/g, '$&,') // 正则先行断言
  return `${integer}${decimal ? '.' + decimal : ''}`
},

注意

num.toFixed is not a function(js报错)
toFixed 是Number类型的方法
所以要改为 num = Number(num).toFixed(2);

posted @ 2021-01-11 16:23  JackieDYH  阅读(5)  评论(0编辑  收藏  举报  来源