Javascript JQuery 数字格式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7327046/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JQuery Number Formatting
提问by Eran Medan
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 pluginis 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 使用的相同格式模式格式化货币、十进制、整数,以便可以格式化客户端接收到的数据,而无需先将其发送到服务器。
e.g.
例如
Format 1000
to $1,000
or 1,000.00
etc (locale support is nice)
格式1000
为$1,000
或1,000.00
等(语言环境支持很好)
Seems that http://plugins.jquery.com/project/numberformatterdoes the job but the question was: "Am I using the right thing?" or "Is there a better way to do so?"
似乎http://plugins.jquery.com/project/numberformatter 可以完成这项工作,但问题是:“我使用的是正确的东西吗?” 或者“有没有更好的方法来做到这一点?”
回答by Abe Miessler
I would recommend looking at this article on how to use javascriptto 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, '' + ',' + '');
}
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. 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 可以以一百万种不同的方式让您的生活更轻松,但我认为这太过分了。请记住,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 outif you want to get a chuckle about the over use of jQuery.
旁注 -如果您想对 jQuery 的过度使用发笑,请查看此内容。
回答by Quadrant6
Using the jQuery Number Formatplugin, 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 )
.number( theNumber、decimalPlaces、decimalSeparator、千位分隔符)
You can also get jQuery Number Format from GitHub.
您还可以从 GitHub获取jQuery 数字格式。
回答by elixon
Browser development progresses:
浏览器开发进展:
Number.toLocaleString(locale);
// E.g.
parseFloat("1234567.891").toLocaleString(window.document.documentElement.lang);
"1,234,567.891"
回答by Luftwaffle
If you need to handle multiple currencies, various number formats etc. I can recommend autoNumeric. Works a treat. Have been using it successfully for several years now.
如果您需要处理多种货币、各种数字格式等,我可以推荐autoNumeric。很好用。已经成功使用它好几年了。
回答by slashka
I wrote a JavaScript analogue of a PHP function number_formaton a base of Abe MiessleraddCommas function. Could be usefull.
我在Abe MiessleraddCommas 函数的基础上编写了一个 PHP 函数number_format的 JavaScript 模拟。可能有用。
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, '' + thousands_sep + '');
return x1 + x2;
}
For example:
例如:
var some_number = number_format(42661.55556, 2, ',', ' '); //gives 42 661,56
回答by slashka
Putting this http://www.mredkj.com/javascript/numberFormat.htmland $('.number').formatNumber();
concept together, you may use the following line of code;
把这个http://www.mredkj.com/javascript/numberFormat.html和$('.number').formatNumber();
概念放在一起,你可以使用下面这行代码;
e.g. <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, '' + ',' + '');
}
$(this).html(x1 + x2);
});
回答by Limitless isa
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
回答by ezwey
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)
}