1. 程式人生 > >js實現千位分隔符 保留兩位小數

js實現千位分隔符 保留兩位小數

function method2() {//新增千位符
	var s = "1531531.351";
	if (/[^0-9\.]/.test(s)) {
		return "invalid value";
	}
	s = s.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");
	alert(s.replace(/^\./, "0."));
}