자바 스크립트 천 구분자 / 문자열 형식
Javascript에 숫자와 문자열을 형식화하는 기능이 있습니까?
문자열 또는 숫자에 대한 천 구분 기호에 대한 방법을 찾고 있습니다 ... (C #의 String.Format처럼)
업데이트 (7 년 후)
아래 원래 답변에 인용 된 참조가 잘못되었습니다. 가 되고 a는 정확히 어떤이에 대한 기능을 내장 카이저는 아래의 제안 :toLocaleString
따라서 다음을 수행 할 수 있습니다.
(1234567.89).toLocaleString('en') // for numeric input
parseFloat("1234567.89").toLocaleString('en') // for string input
아래 구현 된 기능도 작동하지만 단순히 필요하지는 않습니다.
(나는 운이 좋을 것이라고 생각하고 2010 년 에 필요 하다는 것을 알았지 만 그렇지 않습니다. 이보다 신뢰할 수있는 참조 에 따르면 toLocaleString은 ECMAScript 3rd Edition [1999] 이후 표준의 일부였습니다. IE 5.5까지 지원되었을 것입니다.)
원래 답변
이 참조 에 따르면 숫자에 쉼표를 추가하는 기능이 내장되어 있지 않습니다. 그러나이 페이지에는 직접 코딩하는 방법의 예가 포함되어 있습니다.
function addCommas(nStr) {
nStr += '';
var x = nStr.split('.');
var x1 = x[0];
var x2 = x.length > 1 ? '.' + x[1] : '';
var rgx = /(\d+)(\d{3})/;
while (rgx.test(x1)) {
x1 = x1.replace(rgx, '$1' + ',' + '$2');
}
return x1 + x2;
}
편집 : 다른 방법으로 이동하려면 (쉼표가있는 문자열을 숫자로 변환) 다음과 같이 할 수 있습니다.
parseFloat("1,234,567.89".replace(/,/g,''))
대한 경우 현지화 천 단위 구분, 구분 기호와 소수점 구분 기호를, 다음으로 이동 :
// --> numObj.toLocaleString( [locales [, options] ] )
parseInt( number ).toLocaleString();
사용할 수있는 몇 가지 옵션이 있습니다 (대체가있는 로케일도 포함).
number = 123456.7089;
result = parseInt( number ).toLocaleString() + "<br>";
result += number.toLocaleString( 'de-DE' ) + "<br>";
result += number.toLocaleString( 'ar-EG' ) + "<br>";
result += number.toLocaleString( 'ja-JP', {
style : 'currency',
currency : 'JPY',
currencyDisplay : 'symbol',
useGrouping : true
} ) + "<br>";
result += number.toLocaleString( [ 'jav', 'en' ], {
localeMatcher : 'lookup',
style : 'decimal',
minimumIntegerDigits : 2,
minimumFractionDigits : 2,
maximumFractionDigits : 3,
minimumSignificantDigits : 2,
maximumSignificantDigits : 3
} ) + "<br>";
var el = document.getElementById( 'result' );
el.innerHTML = result;
<div id="result"></div>
MDN 정보 페이지 에 대한 세부 정보 .
편집 : 댓글 작성자 @I like Serena 는 다음을 추가합니다.
영어 형식이 필요한 비 영어 로케일의 브라우저를 지원하려면
value.toLocaleString('en')
. 부동 소수점에서도 작동합니다.
ECMAScript2018 변경 사항에 따라 look-behind 지원을 사용하여 업데이트되었습니다.
이전 버전과의 호환성을 위해 더 아래로 스크롤하여 원래 솔루션을 확인하십시오.
정규식을 사용할 수 있습니다. 특히 문자열로 저장된 큰 숫자를 처리하는 데 유용합니다.
const format = num =>
String(num).replace(/(?<!\..*)(\d)(?=(?:\d{3})+(?:\.|$))/g, '$1,')
;[
format(100), // "100"
format(1000), // "1,000"
format(1e10), // "10,000,000,000"
format(1000.001001), // "1,000.001001"
format('100000000000000.001001001001') // "100,000,000,000,000.001001001001
]
.forEach(n => console.log(n))
이 원래 답변은 필수는 아니지만 이전 버전과의 호환성을 위해 사용할 수 있습니다.
단일 정규식 (콜백없이) 으로 이것을 처리하려고 시도하면 현재 능력이 Javascript에서 부정적인 look-behind가 부족하여 실패합니다. 대부분의 일반적인 경우에서 작동하는 또 다른 간결한 대안이 있습니다. 기간 색인 뒤에 일치 색인이 나타나는 일치 항목을 무시합니다.
const format = num => {
const n = String(num),
p = n.indexOf('.')
return n.replace(
/\d(?=(?:\d{3})+(?:\.|$))/g,
(m, i) => p < 0 || i < p ? `${m},` : m
)
}
;[
format(100), // "100"
format(1000), // "1,000"
format(1e10), // "10,000,000,000"
format(1000.001001), // "1,000.001001"
format('100000000000000.001001001001') // "100,000,000,000,000.001001001001
]
.forEach(n => console.log(n))
멋진 jQuery 번호 플러그인이 있습니다 : https://github.com/teamdf/jquery-number
십진수 및 십진수 및 천 단위 구분 문자 옵션을 사용하여 원하는 형식으로 숫자를 변경할 수 있습니다.
$.number(12345.4556, 2); // -> 12,345.46
$.number(12345.4556, 3, ',', ' ') // -> 12 345,456
위와 같은 옵션을 사용하여 입력 필드 내에서 직접 사용할 수 있습니다.
$("input").number(true, 2);
또는 선택기를 사용하여 전체 DOM 요소 집합에 적용 할 수 있습니다.
$('span.number').number(true, 2);
// thousand separates a digit-only string using commas
// by element: onkeyup = "ThousandSeparate(this)"
// by ID: onkeyup = "ThousandSeparate('txt1','lbl1')"
function ThousandSeparate()
{
if (arguments.length == 1)
{
var V = arguments[0].value;
V = V.replace(/,/g,'');
var R = new RegExp('(-?[0-9]+)([0-9]{3})');
while(R.test(V))
{
V = V.replace(R, '$1,$2');
}
arguments[0].value = V;
}
else if ( arguments.length == 2)
{
var V = document.getElementById(arguments[0]).value;
var R = new RegExp('(-?[0-9]+)([0-9]{3})');
while(R.test(V))
{
V = V.replace(R, '$1,$2');
}
document.getElementById(arguments[1]).innerHTML = V;
}
else return false;
}
나는 이것을 사용한다 :
function numberWithCommas(number) {
return number.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
source: link
var number = 35002343;
console.log(number.toLocaleString());
for the reference you can check here https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString
You can use javascript. below are the code, it will only accept
numeric and one dot
here is the javascript
<script >
function FormatCurrency(ctrl) {
//Check if arrow keys are pressed - we want to allow navigation around textbox using arrow keys
if (event.keyCode == 37 || event.keyCode == 38 || event.keyCode == 39 || event.keyCode == 40) {
return;
}
var val = ctrl.value;
val = val.replace(/,/g, "")
ctrl.value = "";
val += '';
x = val.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');
}
ctrl.value = x1 + x2;
}
function CheckNumeric() {
return event.keyCode >= 48 && event.keyCode <= 57 || event.keyCode == 46;
}
</script>
HTML
<input type="text" onkeypress="return CheckNumeric()" onkeyup="FormatCurrency(this)" />
number = 123456.7089;
result = parseInt( number ).toLocaleString() + "<br>";
result = number.toLocaleString( 'pt-BR' ) + "<br>";
var el = document.getElementById( 'result' );
el.innerHTML = result;
<div id="result"></div>
PHP.js has a function to do this called number_format. If you are familiar with PHP it works exactly the same way.
All you need to do is just really this:
123000.9123.toLocaleString()
//result will be "123,000.912"
Combination of solutions for react
let converter = Intl.NumberFormat();
let salary = monthlySalary.replace(/,/g,'')
console.log(converter.format(salary))
this.setState({
monthlySalary: converter.format(salary)
})
}
handleOnChangeMonthlySalary(1000)```
I did not like any of the answers here, so I created a function that worked for me. Just want to share in case anyone else finds it useful.
function getFormattedCurrency(num) {
num = num.toFixed(2)
var cents = (num - Math.floor(num)).toFixed(2);
return Math.floor(num).toLocaleString() + '.' + cents.split('.')[1];
}
참고 URL : https://stackoverflow.com/questions/3753483/javascript-thousand-separator-string-format
'IT박스' 카테고리의 다른 글
Objective-C에서 (bitmask-) 열거 형 선언 및 확인 / 비교 (0) | 2020.10.13 |
---|---|
라이브러리없이 JavaScript에서 IE 9 미만을 확인하는 가장 좋은 방법 (0) | 2020.10.13 |
C / C ++의 최소 double 값 (0) | 2020.10.13 |
결합하는 방법 || (0) | 2020.10.13 |
웹 사이트에서 C #으로 HTML 코드 가져 오기 (0) | 2020.10.13 |