問題描述
我有這些號碼
10999
和 8094
和 456
如果需要的話,我要做的就是在正確的位置添加一個逗號,所以它看起來像這樣
And all i want to do is add a comma in the right place if it needs it so it looks like this
10,999
和 8,094
和 456
這些都在像這樣的 p 標簽中 <p class="points">10999</p>
等等.
These are all within a p tag like this <p class="points">10999</p>
etc.
可以嗎?
我在其他帖子的幫助下在這里嘗試過 http://jsfiddle.net/pdWTU/1/ 但似乎無法讓它工作
I've attempted it here with the help of other posts http://jsfiddle.net/pdWTU/1/ but can't seem to get it to work
謝謝
杰米
更新
搞砸了一點,并設法在這里弄清楚 http://jsfiddle.net/W5jwY/1/
Messed around a bit and managed to figure it out here http://jsfiddle.net/W5jwY/1/
打算看看新的全球化插件,以獲得更好的方法
Going to look at the new Globalization plugin for a better way of doing it
謝謝
杰米
推薦答案
適用于所有瀏覽器,這就是你所需要的.
Works on all browsers, this is all you need.
function commaSeparateNumber(val){
while (/(d+)(d{3})/.test(val.toString())){
val = val.toString().replace(/(d+)(d{3})/, '$1'+','+'$2');
}
return val;
}
感謝正則表達式,將其寫得簡潔明了.這是直接的 JS,但你可以像這樣在 jQuery 中使用它:
Wrote this to be compact, and to the point, thanks to regex. This is straight JS, but you can use it in your jQuery like so:
$('#elementID').html(commaSeparateNumber(1234567890));
或
$('#inputID').val(commaSeparateNumber(1234567890));
但是,如果您需要更清潔、更靈活的東西.下面的代碼將正確修復小數,刪除前導零,并且可以無限使用.感謝評論中的@baacke.
However, if you require something cleaner, with flexibility. The below code will fix decimals correctly, remove leading zeros, and can be used limitlessly. Thanks to @baacke in the comments.
function commaSeparateNumber(val){
val = val.toString().replace(/,/g, ''); //remove existing commas first
var valRZ = val.replace(/^0+/, ''); //remove leading zeros, optional
var valSplit = valRZ.split('.'); //then separate decimals
while (/(d+)(d{3})/.test(valSplit[0].toString())){
valSplit[0] = valSplit[0].toString().replace(/(d+)(d{3})/, '$1'+','+'$2');
}
if(valSplit.length == 2){ //if there were decimals
val = valSplit[0] + "." + valSplit[1]; //add decimals back
}else{
val = valSplit[0]; }
return val;
}
在你的 jQuery 中,像這樣使用:
And in your jQuery, use like so:
$('.your-element').each(function(){
$(this).html(commaSeparateNumber($(this).html()));
});
這里是 jsFiddle.
這篇關于在jQuery中將逗號添加到數字的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!