var NumberFormat = function( places, seperator, unit, prepose ){ this.unit = unit ? unit : ''; this.bits = places ? places : 3; this.prepose = prepose ? true : false; this.seper = seperator ? seperator : ', '; }; NumberFormat.prototype.format = function( source ){ if( source && $.isNumeric( source ) ){ var res, ss = source.toString(), sign = ss.charAt( 0 ), len = this.bits, _index = ss.indexOf( '.' ), l = ss.length; if( _index >= 0 ) l = _index; if( !$.isNumeric( sign ) ){ l = l - 1; ss = ss.substring( 1 ); }else{ sign = ''; } if( len >= l ) return source; var nsize = Math.ceil( l/len ), na = new Array( nsize ), index = 0; for( var i = l; i > 0; i = i-len ){ if( i-len <= 0 ){ na[ index++ ] = ss.substring( i, 0 ); }else{ na[ index++ ] = ss.substring( i, i-len ); } } res = na.reverse().join( this.seper ); if( _index >= 0 ) res += ss.substring( _index + 1 ); if( this.prepose ) res = this.unit + res; else res = res + this.unit; return sign + res; } }; /** * places, seperator, unit, prepose 4个参数的意思: * * places: 几个分为一组,默认3个为一组 * seperator: 分隔符,默认为逗号分隔 * unit: 单位,默认为空 * prepose: 是否把单位前置,默认为不前置 * */ /** * format()方法接受一个参数,需要格式化的数字或者数字字符串,会返回格式化后的结果 */
下面是测试代码:
var nf = new NumberFormat(); var res = nf.format(32342342342342); console.log(res);//32, 342, 342, 342, 342 res = nf.format(-32342342342342); console.log(res);//-32, 342, 342, 342, 342 nf = new NumberFormat(4, '-', '$'); res = nf.format(-32342342342342); console.log(res);//-32-3423-4234-2342$ res = nf.format(32342342342342); console.log(res);//32-3423-4234-2342$