如何使用 jQuery 每三位使用逗号分隔符格式化数字?
例如:
╔═══════════╦═════════════╗
║ Input ║ Output ║
╠═══════════╬═════════════╣
║ 298 ║ 298 ║
║ 2984 ║ 2,984 ║
║ 297312984 ║ 297,312,984 ║
╚═══════════╩═════════════╝
如何使用 jQuery 每三位使用逗号分隔符格式化数字?
例如:
╔═══════════╦═════════════╗
║ Input ║ Output ║
╠═══════════╬═════════════╣
║ 298 ║ 298 ║
║ 2984 ║ 2,984 ║
║ 297312984 ║ 297,312,984 ║
╚═══════════╩═════════════╝
@Paul Creasey 有最简单的正则表达式解决方案,但这里是一个简单的 jQuery 插件:
$.fn.digits = function(){
return this.each(function(){
$(this).text( $(this).text().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,") );
})
}
然后你可以像这样使用它:
$("span.numbers").digits();
你可以使用Number.toLocaleString()
:
var number = 1557564534;
document.body.innerHTML = number.toLocaleString();
// 1,557,564,534
如果您使用正则表达式,则类似这样的东西,不确定替换的确切语法!
MyNumberAsString.replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
你可以试试NumberFormatter。
$(this).format({format:"#,###.00", locale:"us"});
它还支持不同的语言环境,当然包括美国。
这是如何使用它的一个非常简化的示例:
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="jquery.numberformatter.js"></script>
<script>
$(document).ready(function() {
$(".numbers").each(function() {
$(this).format({format:"#,###", locale:"us"});
});
});
</script>
</head>
<body>
<div class="numbers">1000</div>
<div class="numbers">2000000</div>
</body>
</html>
输出:
1,000
2,000,000
2016 年答案:
Javascript有这个功能,所以不需要Jquery。
yournumber.toLocaleString("en");
这不是 jQuery,但它对我有用。取自本站。
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;
}
使用函数编号();
$(function() {
var price1 = 1000;
var price2 = 500000;
var price3 = 15245000;
$("span#s1").html(Number(price1).toLocaleString('en'));
$("span#s2").html(Number(price2).toLocaleString('en'));
$("span#s3").html(Number(price3).toLocaleString('en'));
console.log(Number(price).toLocaleString('en'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<span id="s1"></span><br />
<span id="s2"></span><br />
<span id="s3"></span><br />
这个的核心是replace
调用。到目前为止,我认为任何提议的解决方案都不能处理以下所有情况:
1000 => '1,000'
'1000' => '1,000'
10000.00 => '10,000.00'
'01000.00 => '1,000.00'
'1000.00000' => '1,000.00000'
-
或+
:'-1000.0000' => '-1,000.000'
'1000k' => '1000k'
以下函数完成上述所有操作。
addCommas = function(input){
// If the regex doesn't match, `replace` returns the string unmodified
return (input.toString()).replace(
// Each parentheses group (or 'capture') in this regex becomes an argument
// to the function; in this case, every argument after 'match'
/^([-+]?)(0?)(\d+)(.?)(\d+)$/g, function(match, sign, zeros, before, decimal, after) {
// Less obtrusive than adding 'reverse' method on all strings
var reverseString = function(string) { return string.split('').reverse().join(''); };
// Insert commas every three characters from the right
var insertCommas = function(string) {
// Reverse, because it's easier to do things from the left
var reversed = reverseString(string);
// Add commas every three characters
var reversedWithCommas = reversed.match(/.{1,3}/g).join(',');
// Reverse again (back to normal)
return reverseString(reversedWithCommas);
};
// If there was no decimal, the last capture grabs the final digit, so
// we have to put it back together with the 'before' substring
return sign + (decimal ? insertCommas(before) + decimal + after : insertCommas(before + after));
}
);
};
您可以在这样的 jQuery 插件中使用它:
$.fn.addCommas = function() {
$(this).each(function(){
$(this).text(addCommas($(this).text()));
});
};
您还可以查看 jquery FormatCurrency插件(我是该插件的作者);它也支持多种语言环境,但可能会产生您不需要的货币支持的开销。
$(this).formatCurrency({ symbol: '', roundToDecimalPlace: 0 });
非常简单的方法是使用toLocaleString()
函数
tot = Rs.1402598 //Result : Rs.1402598
tot.toLocaleString() //Result : Rs.1,402,598
更新日期:23/01/2021
变量应该是数字格式。例子 :
Number(tot).toLocaleString() //Result : Rs.1,402,598
这是我的 javascript,仅在 Firefox 和 chrome 上测试
<html>
<header>
<script>
function addCommas(str){
return str.replace(/^0+/, '').replace(/\D/g, "").replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
function test(){
var val = document.getElementById('test').value;
document.getElementById('test').value = addCommas(val);
}
</script>
</header>
<body>
<input id="test" onkeyup="test();">
</body>
</html>
function formatNumberCapture () {
$('#input_id').on('keyup', function () {
$(this).val(function(index, value) {
return value
.replace(/\D/g, "")
.replace(/\B(?=(\d{3})+(?!\d))/g, ",")
;
});
});
你可以试试这个,它对我有用
使用此代码仅添加数字并在 jquery 的输入文本中的三位数后添加逗号:
$(".allow-numeric-addcomma").on("keypress blur", function (e) {
return false;
});
$(".allow-numeric-addcomma").on("keyup", function (e) {
var charCode = (e.which) ? e.which : e.keyCode
if (String.fromCharCode(charCode).match(/[^0-9]/g))
return false;
value = $(this).val().replace(/,/g, '') + e.key;
var nStr = value + '';
nStr = nStr.replace(/\,/g, "");
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');
}
$(this).val(x1 + x2);
return false;
});