格式化金额的函数
/* * 格式化金额, * num为十进制Number类型的原值, * n为保留的小数位数 * return 格式化后的金额字符串 */ function formatNum(num, n){ var numStr = num.toString(), pointIndex = numStr.indexOf('.'), beforePoint, afterPoint; if(pointIndex < 0){ beforePoint = numStr; afterPoint = ''; }else{ beforePoint = numStr.substring(0, pointIndex); if(typeof n == 'undefined'){ afterPoint = numStr.substring(pointIndex); }else{ afterPoint = numStr.substring(pointIndex, pointIndex + n + 1); } } var re = /(-?\d+)(\d{3})/; while(re.test(beforePoint)){ beforePoint = beforePoint.replace(re,"$1,$2"); } return beforePoint + afterPoint; }
格式化输出
/* * 格式化输出, * str为输入的字符串,变量用{}包括 * obj为参数对象 */ function formatStr(str, obj){ for(var name in obj){ str = str.split('{' + name + '}').join(obj[name]); } return str; }
另一种格式化输出
/* * 格式化输出, * str为输入的字符串,变量用{}包括 * arr为参数数组 */ function formatStr(str, arr){ var i,len = arr.length; for(i = 0; i < len; i++){ str = str.split('{' + i + '}').join(arr[i]); } return str; }