標題非常概括我的需求。Angular:使用逗號格式數字
123456789 => 123,456,789
12345 => 12,345
什麼是獲得此轉換的最佳方法?不要在Angular-2中建議貨幣管道,因爲我不需要$或貨幣符號來預先輸出我的輸出。
標題非常概括我的需求。Angular:使用逗號格式數字
123456789 => 123,456,789
12345 => 12,345
什麼是獲得此轉換的最佳方法?不要在Angular-2中建議貨幣管道,因爲我不需要$或貨幣符號來預先輸出我的輸出。
使用DecimalPipe像可在https://angular.io/api/common/DecimalPipe
不使用管道,一個簡單的方法來回答的JavaScript您的問題,這
{{attr | number}}
Working Plunker
文檔:
var str = "The quick brown fox jumps over the lazy dogs.".replace(/(.{2})/g,"$1,");
而且這將輸出Th,e ,qu,ic,k ,br,ow,n ,fo,x ,ju,mp,s ,ov,er, t,he, l,az,y ,do,gs,.
但我認爲你制定你的問題不好,所以,如果你想分析的數字,你應該使用這個功能:
function numberWithCommas(x) {
var parts = x.toString().split(".");
parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
return parts.join(".");
}
所以
var num = numberWithCommas(1234567);
console.log(num);
這將輸出1,234,567
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function printNo() {
document.getElementById('text').innerHTML =
Number(1234355).toLocaleString('en-GB');
}
</script>
</head>
<body onload="printNo()">
<h1 id="text"></h1>
</body>
</html>
https://plnkr.co/edit/OU0koo2r1YuKC1rC3tpN?p=preview https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Number/toLocaleString
可能重複的[如何在JavaScript中使用逗號作爲千位分隔符來打印數字](https://stackoverflow.com/questions/2901102/how-to-print-a-number-with-commas-as千萬分隔符在JavaScript) – gforce301
@ gforce301這是一個不同的環境,因爲CodeWarrior用管道解決方案來回答,所以我們也想爲angular2提供解決方案。 –