js实现数字的格式化

这是在别的地方翻到的代码,但是它原来的有一点小问题,自己把它改进了一下,发出来标记一下,方便自己以后找。。

function numberFormat(num, decimal, dec, spe) { 
     decimal = (undefined === decimal) ? 0 : decimal; 
     decimal = parseInt(decimal); 
     dec  = (undefined === dec) ? '.' : dec; 
     spe  = (undefined === spe) ? ',' : spe; 
     num  = parseFloat(num) + ''; 
 
     var length, tmp, left, right; 
     length = num.length; 
     tmp  = num.split('.', 2); 
     left = tmp[0]; 
     left = _split(left, 3, spe); 
 
     right = (undefined === tmp[1]) ? '' : tmp[1]; 
     right = _pad(right, decimal); 
 
     if (0 == right.length) { 
         num = left; 
     } else { 
         num = left + dec + right; 
     } 
 
     return num; 
 
     function _split(str, len, spe) { 
         var l  = str.length; 
         var tmp = new Array(); 
    
         if (l > len) { 
             var b = l % len; 
 			if(b == 0)
 				b = len;
             var ts = str.substr(0, b); 
             tmp.push(ts); 
    
             while (b < l) { 
                 var ts = str.substr(b, len); 
                 tmp.push(ts); 
                 b += len; 
            } 
           str = tmp.join(spe); 
       } 
    
         return str; 
     } 
    
     function _pad(str, len) { 
         var l = str.length; 
    
         if (l < len) { 
             for (var i = 0; i < (len - l); i++) { 
                  str += '0'; 
            } 
        } else { 
               str = str.substr(0, len); 
        } 
    
         return str; 
     } 
 }

嗯嗯  numberFormat(num, decimal, dec, spe)  

第一个参数是要格式化的数字,

第二个参数是小数点后的位数(可选,默认0),

第三个参数是小数点的样式(可选,默认'.'),

第四个参数是分隔符的样式(可选,默认',')

 

嗯嗯  来个例子:numberFormat(1234,2);  输出为  1,234.00

嗯嗯 大概就是这个样子~

标签: js, numberFormat

添加新评论

icon_question.gificon_razz.gificon_sad.gificon_evil.gificon_exclaim.gificon_smile.gificon_redface.gificon_biggrin.gificon_surprised.gificon_eek.gificon_confused.gificon_cool.gificon_lol.gificon_mad.gificon_twisted.gificon_rolleyes.gificon_wink.gificon_idea.gificon_arrow.gificon_neutral.gificon_cry.gificon_mrgreen.gif