`
txf2004
  • 浏览: 6974134 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

【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. Number.prototype.format = function(format){
  22. if(! isType(format, ’string)) {return ”;} // sanity check
  23. varhasComma = -1 < format.indexOf(’,'),
  24. psplit = format.stripNonNumeric().split(’.'),
  25. that = this;
  26. // compute precision
  27. if(1 < psplit.length) {
  28. // fix number precision
  29. that = that.toFixed(psplit[1].length);
  30. }
  31. // error: too many periods
  32. elseif (2 < psplit.length) {
  33. throw(NumberFormatException: invalidformat, formats should have no more than 1 period: ‘ + format);
  34. }
  35. // remove precision
  36. else{
  37. that = that.toFixed(0);
  38. }
  39. // get the string now that precision is correct
  40. varfnum = that.toString();
  41. // format has comma, then compute commas
  42. if(hasComma) {
  43. // remove precision for computation
  44. psplit = fnum.split(’.');
  45. var cnum = psplit[0],
  46. parr = [],
  47. j = cnum.length,
  48. m = Math.floor(j / 3),
  49. n = cnum.length % 3 || 3; // n cannot be ZERO or causes infinite loop
  50. // break the number into chunks of 3 digits; first chunk may be less than 3
  51. for (var i = 0; i < j; i += n) {
  52. if (i != 0) {n = 3;}
  53. parr[parr.length] = cnum.substr(i, n);
  54. m -= 1;
  55. }
  56. // put chunks back together, separated by comma
  57. fnum = parr.join(’,');
  58. // add the precision back in
  59. if(psplit[1]) {fnum += ‘.’ + psplit[1];}
  60. }
  61. // replace the number portion of the format with fnum
  62. returnformat.replace(/[\d,?\.?]+/, fnum);
  63. };

我们也可以注意到在荷兰或者一些国家逗号,和.号是反过来用的,如 (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. varrgx = /(\d+)(\d{3})/;
  8. while(rgx.test(x1)) {
  9. x1 = x1.replace(rgx, '$1' + ',' + '$2');
  10. }
  11. returnx1 + x2;
  12. }

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

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

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

  1. // This function removes non-numeric characters
  2. functionstripNonNumeric( str )
  3. {
  4. str += '';
  5. varrgx = /^\d|\.|-$/;
  6. varout = '';
  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. returnout;
  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. functionformatNumber(num,dec,thou,pnt,curr1,curr2,n1,n2)
  6. {
  7. varx = Math.round(num * Math.pow(10,dec));
  8. if(x >= 0) n1=n2='';
  9. vary = (''+Math.abs(x)).split('');
  10. varz = y.length - dec;
  11. if(z<0) z--;
  12. for(vari = z; i < 0; i++)
  13. y.unshift('0');
  14. y.splice(z, 0, pnt);
  15. if(y[0] == pnt)y.unshift('0');
  16. while(z > 3)
  17. {
  18. z-=3;
  19. y.splice(z,0,thou);
  20. }
  21. varr = curr1+n1+y.join('')+n2+curr2;
  22. returnr;
  23. }

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. varsnum = new String(pnumber);
  5. varsec = snum.split('.');
  6. varwhole = parseFloat(sec[0]);
  7. varresult = '';
  8. if(sec.length > 1){
  9. vardec = 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. vardot = 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. vardot;
  21. vardec = new String(whole);
  22. dec += '.';
  23. dot = dec.indexOf('.');
  24. while(dec.length <= dot + decimals){ dec += '0'; }
  25. result = dec;
  26. }
  27. returnresult;
  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. case0:
  8. divider =1;
  9. break;
  10. case1:
  11. divider =10;
  12. break;
  13. case2:
  14. divider =100;
  15. break;
  16. default: //for 3 decimal places
  17. divider =1000;
  18. }
  19. workNum=Math.abs((Math.round(anynum*divider)/divider));
  20. workStr=""+workNum
  21. if (workStr.indexOf(".")==-1){workStr+="."}
  22. dStr=workStr.substr(0,workStr.indexOf("."));dNum=dStr-0
  23. pStr=workStr.substr(workStr.indexOf("."))
  24. while (pStr.length-1< decimal){pStr+="0"}
  25. if(pStr =='.') pStr ='';
  26. //--- Adds a comma in the thousands place.
  27. if (dNum>=1000) {
  28. dLen=dStr.length
  29. dStr=parseInt(""+(dNum/1000))+","+dStr.substring(dLen-3,dLen)
  30. }
  31. //-- Adds a comma in the millions place.
  32. if(dNum>=1000000) {
  33. dLen=dStr.length
  34. dStr=parseInt(""+(dNum/1000000))+","+dStr.substring(dLen-7,dLen)
  35. }
  36. retval = dStr + pStr
  37. //-- Put numbers in parentheses if negative.
  38. if (anynum<0) {retval="("+retval+")";}
  39. //You could include a dollar sign in the return value.
  40. //retval = "$"+retval
  41. obj.value = retval;
  42. }




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. Number.prototype.format = function(format){
  22. if(! isType(format, ’string)) {return ”;} // sanity check
  23. varhasComma = -1 < format.indexOf(’,'),
  24. psplit = format.stripNonNumeric().split(’.'),
  25. that = this;
  26. // compute precision
  27. if(1 < psplit.length) {
  28. // fix number precision
  29. that = that.toFixed(psplit[1].length);
  30. }
  31. // error: too many periods
  32. elseif (2 < psplit.length) {
  33. throw(NumberFormatException: invalidformat, formats should have no more than 1 period: ‘ + format);
  34. }
  35. // remove precision
  36. else{
  37. that = that.toFixed(0);
  38. }
  39. color: rgb(
    分享到:
    评论

相关推荐

    mpich.nt.1.2.5

    6. **安装流程**: 解压缩文件后,通常需要运行安装程序(如“mpich.nt.1.2.5.exe”),按照提示进行配置,包括指定安装路径、选择组件、设置环境变量等。 7. **配置MPICH**: 安装后,可能需要配置MPICH以适应特定的...

    Clodop_Setup_for_Win32NT.zip

    标题中的"ClodOP_Setup_for_Win32NT.zip"是一个针对Windows 32位操作系统的安装包,这表明它是一款专为32位Windows系统设计的软件。"ClodOP"通常指的是Cloud Print Operation,它是一个云打印解决方案,允许用户通过...

    CLodop_Setup_for_Win32NT.zip

    CLodop是一款跨平台的云打印解决方案,专为Windows NT操作系统设计。它的全称可能是"Cloud Lodop Online Print",寓意着它提供了一种在线、云端的打印服务。这款组件能够帮助开发者快速集成打印功能,无论是网页应用...

    nt.h ntdll.lib

    在C++编程中,"nt.h" 和 "ntdll.lib" 是两个非常关键的组件,尤其是在Windows操作系统下进行系统级编程时。它们是Windows API的一部分,提供了对内核级功能的访问。 首先,我们来详细了解这两个文件: 1. **nt.h**...

    NT5CC128M16IP-DIA.pdf

    在文件标题中提到的“NT5CC128M16IP-DIA.pdf”是指南亚科技(Nanya Technology Corp)生产的一款DDR3 SDRAM的PDF规格书。从标题和描述来看,这款内存的具体型号是NT5CC128M16IP-DIA,品牌为NANYA。 从描述中可以...

    专业版数据还原软件Final.Data_1.0_NT.2k(还原数据)!

    其中,Final.Data_1.0_NT.2k是一款专为Windows NT/2000系统设计的专业版数据恢复软件,它具备强大的数据还原能力,帮助用户在困境中找回丢失的珍贵数据。 Final.Data_1.0_NT.2k的核心功能主要体现在以下几个方面: ...

    DameWare.NT.Utilities.8.0.0.102 完美破解版

    DameWare.NT.Utilities.8.0.0.102 破解版,亲测win7x64系统可破解,破解后可以使用9999天,分享给有需要的朋友

    实现32位PE下安装32/64位NT5.x/NT6.x,并解决SRS驱动问题的工具

    Win$Man是32/64位Win2000/XP/2003/Vista/2008/2008 R2/7的安装辅助工具,由于MS的安装程序winnt32.exe(nt 5.x)和setup.exe(nt 6.x)有部分限制,大家知道32位PE是无法直接调用winnt32.exe来安装64位系统,而且AHCI、...

    CLodop_Setup_for_Win32NT.exe

    CLodop_Setup_for_Win32NT.exe

    Mysql忘记密码 mysqld-nt.exe文件下载

    2、用另外一种方式启动Mysql:在命令行进入到mysql的安装路径下的bin目录下使用mysqld-nt.exe启动:mysqld-nt –skip-grant-tables 注意:此时CMD窗口不能关闭。 mysqld-nt.exe文件下载 3、进入Mysql:另外打开一个...

    NT6_x和NT5_x 双系统启动修复

    在IT领域,操作系统安装是日常工作中常见的任务,而双系统设置允许用户在同一台电脑上同时运行两个不同的操作系统,如Windows XP(NT5_x)和Windows Vista/7/8/10(NT6_x)。然而,当这样的双系统环境出现问题,特别...

    nt.hdd.installer.rar

    nt6指的是Windows Vista、Windows 7以及Windows 8系列操作系统,因为它们基于NT内核的6.0及更高版本。这个工具能够帮助用户在不使用光盘或USB驱动的情况下,通过硬盘直接安装系统,通常适用于已经拥有系统镜像文件的...

    nt6_3.0.8_XiaZaiBa.zip

    标题中的"nt6_3.0.8_XiaZaiBa.zip"似乎是一个软件或工具的版本标识,可能指的是一个Windows NT6系列操作系统的安装工具,版本为3.0.8,由“XiaZaiBa”(下载吧)提供。在IT行业中,NT6通常是指Windows Vista、...

    NT6.X_HDD_Installer_v3.0 硬盘安装系统软件

    NT6.X HDD Installer_v3.0便是这样一款专为硬盘安装操作系统设计的工具,它允许用户无需光盘或USB驱动器即可完成系统的安装,极大地简化了系统部署的流程。 NT6.x指的是Windows Vista、Windows 7、Windows 8、...

    CLodopPrint_Setup_for_Win32NT_2.048_.exe

    CLodopPrint_Setup_for_Win32NT_2.048_绝对可用.exe Lodop是一款专业的WEB打印控件,其设计目标是简单易用、功能足够强大,开创WEB打印开发的新局面。 Lodop设计者对WEB下的打印开发任务进行了分类汇总,高度抽象,...

    mysqld -nt.exe

    解决没有mysqld.exe -install的问题,下载直接打开可以开启mysql服务,如果不小心删除mysql服务用这个也可以。

Global site tag (gtag.js) - Google Analytics