最近在项目中有跟金额有关的部分,由于数据中不是标准的金额格式的字段,boss要求将数据中金额字段转成标准的金额格式,于是研究了下,现整理成一个函数已用来备用:
//传入的参数s为字符串,返回值也是string类型的
function cc(s) {
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.").toString()
}