当前位置: 代码迷 >> JavaScript >> js 字符串变换
  详细解决方案

js 字符串变换

热度:119   发布时间:2012-06-30 17:20:12.0
js 字符串转换
// 字符串转换 1234567 > 1,234,567
function formatNum(s){
	s = s.toString();
    if (/[^0-9\.]/.test(s)){return "invalid value";}
    s = s.replace(/^(\d*)$/, "$1.");
    s = s.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");
    s = s.substring(0, s.lastIndexOf(','));
    return s
}

console.log(formatNum(1234567)) // 1,234,567

// 字符串转换 1234567 > ¥1,234,567.00
function formatNum(s){
	s = s.toString();
	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");
	return "¥" + s.replace(/^\./,"0.");
}

console.log(formatNum(1234567)) // ¥1,234,567.00
?

?

  相关解决方案