数字工具类
NumberUtils = { /* ** 定义0数字对象 */ zero : Number(0), /* ** 判断是否是数字 */ isNumber:function(val){ if(val == '' || isNaN(val)) { return false; } return true; }, /* ** 返回数字对象 */ toNumber:function(val){ if (this.isNumber(val)) { return Number(val); } else { return this.zero; } }, /* ** 返回整数对象 */ parseInt:function(val){ return this.toNumber(parseInt(val)); }, /* ** 返回小数对象 */ parseFloat:function(val){ return this.toNumber(parseFloat(val)); }, /* ** 返回向上取整后的值 */ ceil:function(val){ return this.toNumber(Math.ceil(val)); }, /* ** 返回小于x的最大整数 */ floor:function(val) { return this.toNumber(Math.floor(val)); }, /* ** 返回四舍五入后的整数 */ round:function(val) { return this.toNumber(Math.round(val)); }, /* ** 返回数字的最接近的单精度浮点型表示 */ fround:function(val){ return this.toNumber(Math.fround(val)); }, /* * 数字格式化 * 参数说明: * number:要格式化的数字 * decimals:保留几位小数 * decPoint:小数点符号 * thousandsMark:千位符号 * roundMode:舍入参数,默认 "ceil" 向上取,"floor"向下取,"round" 四舍五入 */ numberFormat:function(number, decimals, decPoint, thousandsMark, roundMode) { number = (number + '').replace(/[^0-9+-Ee.]/g, ''); roundMode = roundMode || "ceil"; //"ceil","floor","round" var n = !isFinite(+number) ? 0 : +number, prec = !isFinite(+decimals) ? 0 : Math.abs(decimals), sep = (typeof thousandsMark === 'undefined') ? ',' : thousandsMark, dec = (typeof decPoint === 'undefined') ? '.' : decPoint, s = '', toFixedFix = function(n, prec) { var k = Math.pow(10, prec); console.log(); return '' + parseFloat(Math[roundMode](parseFloat((n * k).toFixed(prec * 2))).toFixed(prec * 2)) / k; }; s = (prec ? toFixedFix(n, prec) : '' + Math.round(n)).split('.'); var re = /(-?\d+)(\d{3})/; while (re.test(s[0])) { s[0] = s[0].replace(re, "$1" + sep + "$2"); } if ((s[1] || '').length < prec) { s[1] = s[1] || ''; s[1] += new Array(prec - s[1].length + 1).join('0'); } return s.join(dec); } }

更多精彩