简体   繁体   English

JQuery数字格式

[英]JQuery Number Formatting

There are way too many questions and answers about this basic functionality, I cannot see the wood for the trees. 关于这个基本功能有太多的问题和答案,我看不到树木的木材。

In Java there is only one simple answer ( java.text.NumberFormat and its subclasses) so I'm sure the majority of plugins, questions and answers will mature eventually to a de-facto standard for JQuery. 在Java中只有一个简单的答案( java.text.NumberFormat及其子类),所以我确信大多数插件,问题和答案最终都会成熟为JQuery的事实标准。

This plugin is the best I found so far, but I don't know if it's still developed, is mature etc. 这个插件是我迄今为止发现的最好的插件 ,但我不知道它是否仍在开发中,是否成熟等。

http://plugins.jquery.com/project/numberformatter http://plugins.jquery.com/project/numberformatter

Is there a better solution? 有更好的解决方案吗? Is it mature / active enough to rely on? 它是否足够成熟/活跃?


Edit: 编辑:

I would like to be able to format currencies, decimal, integers based on the same format patterns Java uses, so that data recieved on the client side can be formatted without sending it first to the server. 我希望能够基于Java使用的相同格式模式格式化货币,十进制,整数,以便可以格式化客户端收到的数据,而无需先将其发送到服务器。

eg 例如

Format 1000 to $1,000 or 1,000.00 etc (locale support is nice) 格式1000$1,0001,000.00等(区域设置支持很好)

Seems that http://plugins.jquery.com/project/numberformatter does the job but the question was: "Am I using the right thing?" 似乎http://plugins.jquery.com/project/numberformatter完成了这项工作,但问题是:“我使用的是正确的吗?” or "Is there a better way to do so?" 或者“有更好的方法吗?”

I would recommend looking at this article on how to use javascript to handle basic formatting: 我建议看看这篇关于如何使用javascript来处理基本格式的文章:

function addCommas(nStr)
{
    nStr += '';
    x = nStr.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
}

source: http://www.mredkj.com/javascript/numberFormat.html 来源: http//www.mredkj.com/javascript/numberFormat.html

While jQuery can make your life easier in a million different ways I would say it's overkill for this. 虽然jQuery可以通过百万种不同的方式让你的生活更轻松,但我认为这样做太过分了。 Keep in mind that jQuery can be fairly large and your user's browser needs to download it when you use it on a page. 请记住,jQuery可能相当大,当您在页面上使用它时,用户的浏览器需要下载它。

When ever using jQuery you should step back and ask if it contributes enough to justify the extra overhead of downloading the library. 当你使用jQuery时,你应该退后一步,询问它是否足以证明下载库的额外开销。

If you need some sort of advanced formatting (like the localization stuff in the plugin you linked), or you are already including jQuery it might be worth looking at a jQuery plugin. 如果您需要某种高级格式(如您链接的插件中的本地化内容),或者您已经包含jQuery,那么可能值得查看jQuery插件。

Side note - check this out if you want to get a chuckle about the over use of jQuery. 旁注 - 如果你想对过度使用jQuery轻笑一下, 请检查一下。

Using the jQuery Number Format plugin, you can get a formatted number in one of three ways: 使用jQuery Number Format插件,您可以通过以下三种方式之一获取格式化的数字:

// Return as a string
$.number( 1234.5678, 2 ); // Returns '1,234.57'

// Place formatted number directly in an element:
$('#mynum').number( 1234.5678 ); // #mynum would then contain '1,235'

// Replace existing number values in any element
$('span.num').number( true, 2 ); // Formats and replaces existing numbers in those elements.

If you don't like the format, or you need to localise, there are other parameters that let you choose how the number gets formatted: 如果您不喜欢该格式,或者您需要进行本地化,则可以使用其他参数来选择数字的格式:

.number( theNumber, decimalPlaces, decimalSeparator, thousandsSeparator ) .nu​​mber(theNumber,decimalPlaces,decimalSeparator,thousandsSeparator)

You can also get jQuery Number Format from GitHub . 您还可以从GitHub获取jQuery数字格式

Browser development progresses: 浏览器开发进度:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString

 Number.toLocaleString(locale);

 // E.g.
 parseFloat("1234567.891").toLocaleString(window.document.documentElement.lang);
 "1,234,567.891"

If you need to handle multiple currencies, various number formats etc. I can recommend autoNumeric . 如果您需要处理多种货币,各种数字格式等,我可以推荐autoNumeric Works a treat. 工作一种享受。 Have been using it successfully for several years now. 几年来一直成功使用它。

Putting this http://www.mredkj.com/javascript/numberFormat.html and $('.number').formatNumber(); 把这个http://www.mredkj.com/javascript/numberFormat.html$('.number').formatNumber(); concept together, you may use the following line of code; 概念在一起,您可以使用以下代码行;

eg <td class="number">1172907.50</td> will be formatted like <td class="number">1,172,907.50</td> 例如<td class="number">1172907.50</td>格式为<td class="number">1,172,907.50</td>

$('.number').text(function () { 
    var str = $(this).html() + ''; 
    x = str.split('.'); 
    x1 = x[0]; x2 = x.length > 1 ? '.' + x[1] : ''; 
    var rgx = /(\d+)(\d{3})/; 
    while (rgx.test(x1)) { 
        x1 = x1.replace(rgx, '$1' + ',' + '$2'); 
    } 
    $(this).html(x1 + x2); 
});

http://jquerypriceformat.com/#examples http://jquerypriceformat.com/#examples

https://github.com/flaviosilveira/Jquery-Price-Format https://github.com/flaviosilveira/Jquery-Price-Format

html input runing for live chance. html输入运行的机会。

<input type="text" name="v7"  class="priceformat"/>
<input type="text" name="v8"  class="priceformat"/>


$('.priceformat').each(function( index ) {
    $(this).priceFormat({ prefix: '',  thousandsSeparator: '' });
});

//5000.00 //5000.00

//5.000,00 //5.000,00

//5,000.00 //5,000.00

I wrote a JavaScript analogue of a PHP function number_format on a base of Abe Miessler addCommas function. 我在Abe Miessler addCommas函数的基础上编写了一个PHP函数number_format的JavaScript模拟。 Could be usefull. 可能有用。

number_format = function (number, decimals, dec_point, thousands_sep) {
        number = number.toFixed(decimals);

        var nstr = number.toString();
        nstr += '';
        x = nstr.split('.');
        x1 = x[0];
        x2 = x.length > 1 ? dec_point + x[1] : '';
        var rgx = /(\d+)(\d{3})/;

        while (rgx.test(x1))
            x1 = x1.replace(rgx, '$1' + thousands_sep + '$2');

        return x1 + x2;
    }

For example: 例如:

var some_number = number_format(42661.55556, 2, ',', ' '); //gives 42 661,56

http://locutus.io/php/strings/number_format/ http://locutus.io/php/strings/number_format/

module.exports = function number_format (number, decimals, decPoint, thousandsSep) { // eslint-disable-enter code hereline camelcase
  //  discuss at: http://locutus.io/php/number_format/
  // original by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
  // improved by: Kevin van Zonneveld (http://kvz.io)
  // improved by: davook
  // improved by: Brett Zamir (http://brett-zamir.me)
  // improved by: Brett Zamir (http://brett-zamir.me)
  // improved by: Theriault (https://github.com/Theriault)
  // improved by: Kevin van Zonneveld (http://kvz.io)
  // bugfixed by: Michael White (http://getsprink.com)
  // bugfixed by: Benjamin Lupton
  // bugfixed by: Allan Jensen (http://www.winternet.no)
  // bugfixed by: Howard Yeend
  // bugfixed by: Diogo Resende
  // bugfixed by: Rival
  // bugfixed by: Brett Zamir (http://brett-zamir.me)
  //  revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
  //  revised by: Luke Smith (http://lucassmith.name)
  //    input by: Kheang Hok Chin (http://www.distantia.ca/)
  //    input by: Jay Klehr
  //    input by: Amir Habibi (http://www.residence-mixte.com/)
  //    input by: Amirouche
  //   example 1: number_format(1234.56)
  //   returns 1: '1,235'
  //   example 2: number_format(1234.56, 2, ',', ' ')
  //   returns 2: '1 234,56'
  //   example 3: number_format(1234.5678, 2, '.', '')
  //   returns 3: '1234.57'
  //   example 4: number_format(67, 2, ',', '.')
  //   returns 4: '67,00'
  //   example 5: number_format(1000)
  //   returns 5: '1,000'
  //   example 6: number_format(67.311, 2)
  //   returns 6: '67.31'
  //   example 7: number_format(1000.55, 1)
  //   returns 7: '1,000.6'
  //   example 8: number_format(67000, 5, ',', '.')
  //   returns 8: '67.000,00000'
  //   example 9: number_format(0.9, 0)
  //   returns 9: '1'
  //  example 10: number_format('1.20', 2)
  //  returns 10: '1.20'
  //  example 11: number_format('1.20', 4)
  //  returns 11: '1.2000'
  //  example 12: number_format('1.2000', 3)
  //  returns 12: '1.200'
  //  example 13: number_format('1 000,50', 2, '.', ' ')
  //  returns 13: '100 050.00'
  //  example 14: number_format(1e-8, 8, '.', '')
  //  returns 14: '0.00000001'

  number = (number + '').replace(/[^0-9+\-Ee.]/g, '')
  var n = !isFinite(+number) ? 0 : +number
  var prec = !isFinite(+decimals) ? 0 : Math.abs(decimals)
  var sep = (typeof thousandsSep === 'undefined') ? ',' : thousandsSep
  var dec = (typeof decPoint === 'undefined') ? '.' : decPoint
  var s = ''

  var toFixedFix = function (n, prec) {
    if (('' + n).indexOf('e') === -1) {
      return +(Math.round(n + 'e+' + prec) + 'e-' + prec)
    } else {
      var arr = ('' + n).split('e')
      var sig = ''
      if (+arr[1] + prec > 0) {
        sig = '+'
      }
      return (+(Math.round(+arr[0] + 'e' + sig + (+arr[1] + prec)) + 'e-' + prec)).toFixed(prec)
    }
  }

  // @todo: for IE parseFloat(0.55).toFixed(0) = 0;
  s = (prec ? toFixedFix(n, prec).toString() : '' + Math.round(n)).split('.')
  if (s[0].length > 3) {
    s[0] = s[0].replace(/\B(?=(?:\d{3})+(?!\d))/g, sep)
  }
  if ((s[1] || '').length < prec) {
    s[1] = s[1] || ''
    s[1] += new Array(prec - s[1].length + 1).join('0')
  }

  return s.join(dec)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM