세 자리 숫자마다 쉼표를 추가하십시오
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
정규 표현식을 사용하는 경우 이와 같은 것이 있습니다. 대체 tho의 정확한 구문을 모릅니다!
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
이것은 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;
}
2016 년 답변 :
Javascript에는이 기능이 있으므로 Jquery가 필요하지 않습니다.
yournumber.toLocaleString("en");
함수 사용 Number ();
$(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 />
보다 철저한 솔루션
The core of this is the replace
call. So far, I don't think any of the proposed solutions handle all of the following cases:
- Integers:
1000 => '1,000'
- Strings:
'1000' => '1,000'
- For strings:
- Preserves zeros after decimal:
10000.00 => '10,000.00'
- Discards leading zeros before decimal:
'01000.00 => '1,000.00'
- Does not add commas after decimal:
'1000.00000' => '1,000.00000'
- Preserves leading
-
or+
:'-1000.0000' => '-1,000.000'
- Returns, unmodified, strings containing non-digits:
'1000k' => '1000k'
- Preserves zeros after decimal:
The following function does all of the above.
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));
}
);
};
You could use it in a jQuery plugin like this:
$.fn.addCommas = function() {
$(this).each(function(){
$(this).text(addCommas($(this).text()));
});
};
You can also look at the jquery FormatCurrency plugin (of which I am the author); it has support for multiple locales as well, but may have the overhead of the currency support that you don't need.
$(this).formatCurrency({ symbol: '', roundToDecimalPlace: 0 });
Here is my javascript, tested on firefox and chrome only
<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>
Very Easy way is to use toLocaleString()
function
tot = Rs.1402598 //Result : Rs.1402598
tot.toLocaleString() //Result : Rs.1,402,598
참고URL : https://stackoverflow.com/questions/1990512/add-comma-to-numbers-every-three-digits
'Programing' 카테고리의 다른 글
Xcode 7.2 일치하는 프로비저닝 프로파일이 없습니다. (0) | 2020.06.14 |
---|---|
MySQL : 조인 유형의 빠른 분석 (0) | 2020.06.14 |
AngularJS 빠른 검색을 지연시키는 방법은 무엇입니까? (0) | 2020.06.13 |
Jupyter Notebook의 파일에서 이미지를 표시하려면 어떻게해야합니까? (0) | 2020.06.13 |
iPhone에서 Objective-C로 메소드 이름 NSLog (0) | 2020.06.13 |