【NT.CC】6款非常有用的JS数值格式

6款非常有用的JS数值格式

JS里面数值是如何处理的呢?因为JS不是类型那个严格的语言,因此+号也是连接号,你可以非常简单的通过+号转换为数值,但是我们也知道JS没有很多内建的处理数据格式的函数,我们必须自己来定义,下面6个就是非常经典的6个,我们需要重头开始么?当然不需要,COPY ->PASTE


当然如果你有什么创举的话,不要仅仅将其藏在硬盘上,拿出来让大家看看。

No.1 by Matt:

NO.1 使用格式传来格式化数字,这是C里面常用的形式,当然JS里面也可以了

  1. /**
  2. * Formats the number according to the ‘format’ string;
  3. * adherses to the american number standard where a comma
  4. * is inserted after every 3 digits.
  5. note: there should be only 1 contiguous number in the format,
  6. * where a number consists of digits, period, and commas
  7. *        any other characters can be wrapped around this number, including ‘$’, ‘%’, or text
  8. *        examples (123456.789):
  9. *          ‘0′ - (123456) show only digits, no precision不显示小数部分
  10. *          ‘0.00′ - (123456.78) show only digits, 2 precision两位小数
  11. *          ‘0.0000′ - (123456.7890) show only digits, 4 precision
  12. *          ‘0,000′ - (123,456) show comma and digits, no precision
  13. *          ‘0,000.00′ - (123,456.78) show comma and digits, 2 precision分号分隔
  14. *          ‘0,0.00′ - (123,456.78) shortcut method, show comma and digits, 2 precision
  15. *
  16. * @method format
  17. * @param format {string} the way you would like to format this text
  18. * @return {string} the formatted number
  19. * @public
  20. */ 
  21.  
  22. Number.prototype.format = function(format) {
  23.   if (! isType(format, ’string)) {return ”;} // sanity check
  24.  
  25.   var hasComma = -1 < format.indexOf(’,'),
  26.     psplit = format.stripNonNumeric().split(’.'),
  27.     that = this;
  28.  
  29.   // compute precision
  30.   if (1 < psplit.length) {
  31.     // fix number precision
  32.     that = that.toFixed(psplit[1].length);
  33.   }
  34.   // error: too many periods
  35.   else if (2 < psplit.length) {
  36.     throw(NumberFormatException: invalid format, formats should have no more than 1 period: ‘ + format);
  37.   }
  38.   // remove precision
  39.   else {
  40.     that = that.toFixed(0);
  41.   } 
  42.  
  43.   // get the string now that precision is correct
  44.   var fnum = that.toString();
  45.  
  46.   // format has comma, then compute commas
  47.   if (hasComma) {
  48.     // remove precision for computation
  49.     psplit = fnum.split(’.');
  50.  
  51.     var cnum = psplit[0],
  52.       parr = [],
  53.       j = cnum.length,
  54.       m = Math.floor(j / 3),
  55.       n = cnum.length % 3 || 3; // n cannot be ZERO or causes infinite loop
  56.  
  57.     // break the number into chunks of 3 digits; first chunk may be less than 3
  58.     for (var i = 0; i < j; i += n) {
  59.       if (i != 0) {n = 3;}
  60.       parr[parr.length] = cnum.substr(i, n);
  61.       m -= 1;
  62.     }
  63.  
  64.     // put chunks back together, separated by comma
  65.     fnum = parr.join(’,');
  66.  
  67.     // add the precision back in
  68.     if (psplit[1]) {fnum += ‘.’ + psplit[1];}
  69.   } 
  70.  
  71.   // replace the number portion of the format with fnum
  72.   return format.replace(/[/d,?/.?]+/, fnum);
  73. };

我们也可以注意到在荷兰或者一些国家逗号,和.号是反过来用的,如 (e.g. 1.234,56 而不是 1,234.45)但是我想转换起来也不麻烦

No.2  by Mredkj (Add commas)

NO.2高级的正则表达式实现版

  1. function addCommas(nStr)
  2. {
  3.   nStr += '';
  4.   x = nStr.split('.');
  5.   x1 = x[0];
  6.   x2 = x.length > 1 ? '.' + x[1] : '';
  7.   var rgx = /(/d+)(/d{3})/;
  8.   while (rgx.test(x1)) {
  9.     x1 = x1.replace(rgx, '$1' + ',' + '$2');
  10.   }
  11.   return x1 + x2;
  12. }

No.3 by netlobo(Strip Non-Numeric Characters From a String)

NO.3将非数值字符从字符串中剥离【正则表达式实现】

这个函数将字符串中的所有非数值字符从中玻璃,从而只剩下数值部分,该实现考虑了-号和.点,这两个符号不会被剥离,除非-号出现在中间,而.号超过一个

  1. // This function removes non-numeric characters
  2. function stripNonNumeric( str )
  3. {
  4.   str += '';
  5.   var rgx = /^/d|/.|-$/;
  6.   var out = '';
  7.   for( var i = 0; i < str.length; i++ )
  8.   {
  9.     if( rgx.test( str.charAt(i) ) ){
  10.       if( !( ( str.charAt(i) == '.' && out.indexOf( '.' ) != -1 ) ||
  11.              ( str.charAt(i) == '-' && out.length != 0 ) ) ){
  12.         out += str.charAt(i);
  13.       }
  14.     }
  15.   }
  16.   return out;
  17. }

No.4 by Stephen Chapman

NO.4通脱这个函数我们可以通过其8个参数任意的选择数值的不同格式化形式

  1. // number formatting function
  2. // copyright Stephen Chapman 24th March 2006, 10th February 2007
  3. // permission to use this function is granted provided
  4. // that this copyright notice is retained intact
  5. function formatNumber(num,dec,thou,pnt,curr1,curr2,n1,n2) 
  6. {
  7.   var x = Math.round(num * Math.pow(10,dec));
  8.   if (x >= 0) n1=n2='';
  9.  
  10.   var y = (''+Math.abs(x)).split('');
  11.   var z = y.length - dec;
  12.  
  13.   if (z<0) z--;
  14.  
  15.   for(var i = z; i < 0; i++) 
  16.     y.unshift('0');
  17.  
  18.   y.splice(z, 0, pnt);
  19.   if(y[0] == pnt) y.unshift('0');
  20.  
  21.   while (z > 3) 
  22.   {
  23.     z-=3;
  24.     y.splice(z,0,thou);
  25.   } 
  26.  
  27.   var r = curr1+n1+y.join('')+n2+curr2;
  28.   return r;
  29. }

No.5 by java-scripts

NO.5这个函数通过一些确定的十进制格式将传入的数值格式化,注意小数值并不会被圆整

  1. function format_number(pnumber,decimals){
  2.     if (isNaN(pnumber)) { return 0};
  3.     if (pnumber=='') { return 0};
  4.     var snum = new String(pnumber);
  5.     var sec = snum.split('.');
  6.     var whole = parseFloat(sec[0]);
  7.     var result = '';
  8.     if(sec.length > 1){
  9.         var dec = new String(sec[1]);
  10.         dec = String(parseFloat(sec[1])/Math.pow(10,(dec.length - decimals)));
  11.         dec = String(whole + Math.round(parseFloat(dec))/Math.pow(10,decimals));
  12.         var dot = dec.indexOf('.');
  13.         if(dot == -1){
  14.             dec += '.';
  15.             dot = dec.indexOf('.');
  16.         }
  17.         while(dec.length <= dot + decimals) { dec += '0'; }
  18.         result = dec;
  19.     } else{
  20.         var dot;
  21.         var dec = new String(whole);
  22.         dec += '.';
  23.         dot = dec.indexOf('.');       
  24.         while(dec.length <= dot + decimals) { dec += '0'; }
  25.         result = dec;
  26.     }   
  27.     return result;
  28. }

No.6 by geocities


  1. function formatNumber (obj, decimal) {
  2.      //decimal  - the number of decimals after the digit from 0 to 3
  3.      //-- Returns the passed number as a string in the xxx,xxx.xx format.
  4.        anynum=eval(obj.value);
  5.        divider =10;
  6.        switch(decimal){
  7.             case 0:
  8.                 divider =1;
  9.                 break;
  10.             case 1:
  11.                 divider =10;
  12.                 break;
  13.             case 2:
  14.                 divider =100;
  15.                 break;
  16.             default:       //for 3 decimal places
  17.                 divider =1000;
  18.         } 
  19.  
  20.        workNum=Math.abs((Math.round(anynum*divider)/divider));
  21.  
  22.        workStr=""+workNum
  23.  
  24.        if (workStr.indexOf(".")==-1){workStr+="."}
  25.  
  26.        dStr=workStr.substr(0,workStr.indexOf("."));dNum=dStr-0
  27.        pStr=workStr.substr(workStr.indexOf("."))
  28.  
  29.        while (pStr.length-1< decimal){pStr+="0"}
  30.  
  31.        if(pStr =='.') pStr ='';
  32.  
  33.        //--- Adds a comma in the thousands place.   
  34.        if (dNum>=1000) {
  35.           dLen=dStr.length
  36.           dStr=parseInt(""+(dNum/1000))+","+dStr.substring(dLen-3,dLen)
  37.        } 
  38.  
  39.        //-- Adds a comma in the millions place.
  40.        if (dNum>=1000000) {
  41.           dLen=dStr.length
  42.           dStr=parseInt(""+(dNum/1000000))+","+dStr.substring(dLen-7,dLen)
  43.        }
  44.        retval = dStr + pStr
  45.        //-- Put numbers in parentheses if negative.
  46.        if (anynum<0) {retval="("+retval+")";}
  47.  
  48.     //You could include a dollar sign in the return value.
  49.       //retval =  "$"+retval
  50.       obj.value = retval;
  51. }

 


 




How number is treated in JavaScript? JavaScript is loosely typed and the plus operator also concatenates, you can easily convert JavaScript Numbers to Strings similar to this: 1 + “”, but as we all know that JavaScript doesn’t have many built-in methods to format numbers. Most of the time we need to write our customized code to do it.The following is 6 very useful JavaScript number format function,why have to re-inventing the wheel? Don’t waste your valuable time to write it by yourself, only copy which you like and use it!

Of course if you had wrote your proudly number format function,don’t only stock in your hard disk( or your head), let’s share!

No.1 by Matt:

Basically, you can pass in a String as the format that contain any one number,and the result will replace the number in the format String with the properly formatted Number object. See the comment block for details.

  1. /**
  2. * Formats the number according to the ‘format’ string;
  3. * adherses to the american number standard where a comma
  4. * is inserted after every 3 digits.
  5. note: there should be only 1 contiguous number in the format,
  6. * where a number consists of digits, period, and commas
  7. *        any other characters can be wrapped around this number, including ‘$’, ‘%’, or text
  8. *        examples (123456.789):
  9. *          ‘0′ - (123456) show only digits, no precision
  10. *          ‘0.00′ - (123456.78) show only digits, 2 precision
  11. *          ‘0.0000′ - (123456.7890) show only digits, 4 precision
  12. *          ‘0,000′ - (123,456) show comma and digits, no precision
  13. *          ‘0,000.00′ - (123,456.78) show comma and digits, 2 precision
  14. *          ‘0,0.00′ - (123,456.78) shortcut method, show comma and digits, 2 precision
  15. *
  16. * @method format
  17. * @param format {string} the way you would like to format this text
  18. * @return {string} the formatted number
  19. * @public
  20. */ 
  21.  
  22. Number.prototype.format = function(format) {
  23.   if (! isType(format, ’string)) {return ”;} // sanity check
  24.  
  25.   var hasComma = -1 < format.indexOf(’,'),
  26.     psplit = format.stripNonNumeric().split(’.'),
  27.     that = this;
  28.  
  29.   // compute precision
  30.   if (1 < psplit.length) {
  31.     // fix number precision
  32.     that = that.toFixed(psplit[1].length);
  33.   }
  34.   // error: too many periods
  35.   else if (2 < psplit.length) {
  36.     throw(NumberFormatException: invalid format, formats should have no more than 1 period: ‘ + format);
  37.   }
  38.   // remove precision
  39.   else {
  40.     that = that.toFixed(0);
  41.   } 
  42.  
  43.   // get the string now that precision is correct
  44.   var fnum = that.toString();
  45.  
  46.   // format has comma, then compute commas
  47.   if (hasComma) {
  48.     // remove precision for computation
  49.     psplit = fnum.split(’.');
  50.  
  51.     var cnum = psplit[0],
  52.       parr = [],
  53.       j = cnum.length,
  54.       m = Math.floor(j / 3),
  55.       n = cnum.length % 3 || 3; // n cannot be ZERO or causes infinite loop
  56.  
  57.     // break the number into chunks of 3 digits; first chunk may be less than 3
  58.     for (var i = 0; i < j; i += n) {
  59.       if (i != 0) {n = 3;}
  60.       parr[parr.length] = cnum.substr(i, n);
  61.       m -= 1;
  62.     }
  63.  
  64.     // put chunks back together, separated by comma
  65.     fnum = parr.join(’,');
  66.  
  67.     // add the precision back in
  68.     if (psplit[1]) {fnum += ‘.’ + psplit[1];}
  69.   } 
  70.  
  71.   // replace the number portion of the format with fnum
  72.   return format.replace(/[/d,?/.?]+/, fnum);
  73. };

I noticed that some countries (e.g. Netherlands) use the comma and period exactly opposite (e.g. 1.234,56 instead of 1,234.45) ,but it can be easily modified.

No.2  by Mredkj (Add commas)

  1. function addCommas(nStr)
  2. {
  3.   nStr += '';
  4.   x = nStr.split('.');
  5.   x1 = x[0];
  6.   x2 = x.length > 1 ? '.' + x[1] : '';
  7.   var rgx = /(/d+)(/d{3})/;
  8.   while (rgx.test(x1)) {
  9.     x1 = x1.replace(rgx, '$1' + ',' + '$2');
  10.   }
  11.   return x1 + x2;
  12. }

No.3 by netlobo(Strip Non-Numeric Characters From a String) 

This function strips any non-numeric characters from a string leaving you with a valid decimal number. This function considers the minus sign (hyphen) and the period to be numeric and will not strip them unless the minus sign is not at the beginning of the number or there is more than one period:

  1. // This function removes non-numeric characters
  2. function stripNonNumeric( str )
  3. {
  4.   str += '';
  5.   var rgx = /^/d|/.|-$/;
  6.   var out = '';
  7.   for( var i = 0; i < str.length; i++ )
  8.   {
  9.     if( rgx.test( str.charAt(i) ) ){
  10.       if( !( ( str.charAt(i) == '.' && out.indexOf( '.' ) != -1 ) ||
  11.              ( str.charAt(i) == '-' && out.length != 0 ) ) ){
  12.         out += str.charAt(i);
  13.       }
  14.     }
  15.   }
  16.   return out;
  17. }

No.4 by Stephen Chapman

With this function,we can easily select different formatting by changing the values in the second through eighth parameters. The second parameter is the number of decimal places that the number should have.

  1. // number formatting function
  2. // copyright Stephen Chapman 24th March 2006, 10th February 2007
  3. // permission to use this function is granted provided
  4. // that this copyright notice is retained intact
  5. function formatNumber(num,dec,thou,pnt,curr1,curr2,n1,n2) 
  6. {
  7.   var x = Math.round(num * Math.pow(10,dec));
  8.   if (x >= 0) n1=n2='';
  9.  
  10.   var y = (''+Math.abs(x)).split('');
  11.   var z = y.length - dec;
  12.  
  13.   if (z<0) z--;
  14.  
  15.   for(var i = z; i < 0; i++) 
  16.     y.unshift('0');
  17.  
  18.   y.splice(z, 0, pnt);
  19.   if(y[0] == pnt) y.unshift('0');
  20.  
  21.   while (z > 3) 
  22.   {
  23.     z-=3;
  24.     y.splice(z,0,thou);
  25.   } 
  26.  
  27.   var r = curr1+n1+y.join('')+n2+curr2;
  28.   return r;
  29. }

No.5 by java-scripts

This function formats a numeric value passed in to it with specified number of decimal values. Numeric value will not be rounded.

  1. function format_number(pnumber,decimals){
  2.     if (isNaN(pnumber)) { return 0};
  3.     if (pnumber=='') { return 0};
  4.     var snum = new String(pnumber);
  5.     var sec = snum.split('.');
  6.     var whole = parseFloat(sec[0]);
  7.     var result = '';
  8.     if(sec.length > 1){
  9.         var dec = new String(sec[1]);
  10.         dec = String(parseFloat(sec[1])/Math.pow(10,(dec.length - decimals)));
  11.         dec = String(whole + Math.round(parseFloat(dec))/Math.pow(10,decimals));
  12.         var dot = dec.indexOf('.');
  13.         if(dot == -1){
  14.             dec += '.';
  15.             dot = dec.indexOf('.');
  16.         }
  17.         while(dec.length <= dot + decimals) { dec += '0'; }
  18.         result = dec;
  19.     } else{
  20.         var dot;
  21.         var dec = new String(whole);
  22.         dec += '.';
  23.         dot = dec.indexOf('.');       
  24.         while(dec.length <= dot + decimals) { dec += '0'; }
  25.         result = dec;
  26.     }   
  27.     return result;
  28. }

No.6 by geocities

This function formats a number with a number of decimal places from 0 to 3.

  1. function formatNumber (obj, decimal) {
  2.      //decimal  - the number of decimals after the digit from 0 to 3
  3.      //-- Returns the passed number as a string in the xxx,xxx.xx format.
  4.        anynum=eval(obj.value);
  5.        divider =10;
  6.        switch(decimal){
  7.             case 0:
  8.                 divider =1;
  9.                 break;
  10.             case 1:
  11.                 divider =10;
  12.                 break;
  13.             case 2:
  14.                 divider =100;
  15.                 break;
  16.             default:       //for 3 decimal places
  17.                 divider =1000;
  18.         } 
  19.  
  20.        workNum=Math.abs((Math.round(anynum*divider)/divider));
  21.  
  22.        workStr=""+workNum
  23.  
  24.        if (workStr.indexOf(".")==-1){workStr+="."}
  25.  
  26.        dStr=workStr.substr(0,workStr.indexOf("."));dNum=dStr-0
  27.        pStr=workStr.substr(workStr.indexOf("."))
  28.  
  29.        while (pStr.length-1< decimal){pStr+="0"}
  30.  
  31.        if(pStr =='.') pStr ='';
  32.  
  33.        //--- Adds a comma in the thousands place.   
  34.        if (dNum>=1000) {
  35.           dLen=dStr.length
  36.           dStr=parseInt(""+(dNum/1000))+","+dStr.substring(dLen-3,dLen)
  37.        } 
  38.  
  39.        //-- Adds a comma in the millions place.
  40.        if (dNum>=1000000) {
  41.           dLen=dStr.length
  42.           dStr=parseInt(""+(dNum/1000000))+","+dStr.substring(dLen-7,dLen)
  43.        }
  44.        retval = dStr + pStr
  45.        //-- Put numbers in parentheses if negative.
  46.        if (anynum<0) {retval="("+retval+")";}
  47.  
  48.     //You could include a dollar sign in the return value.
  49.       //retval =  "$"+retval
  50.       obj.value = retval;
  51. }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值