2017-02-15 33 views
0

我有一個角2 /打字稿的應用程序,包含數表示,如下面...轉換數字字符串,以逗號版本

10000.50

-10000

-10000.50

我想在逗號添加千元大關後,例如...

10,000.50

-10,000

-10,000.50

這樣做的最佳方法是什麼?

我已經嘗試了一些其他的答案,但沒有什麼是完全正確的。

例如this.value.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,");this.value.toLocaleString();似乎無法處理comman和小數點。

+0

你考慮使用管道? https://angular.io/docs/ts/latest/api/common/index/CurrencyPipe-pipe.html – Saravana

+0

由於您使用的是Angular2,請嘗試使用DecimalPipe(在視圖或組件/服務中)。 – Zyga

+0

看到這個帖子 http://stackoverflow.com/questions/2901102/how-to-print-a-number-with-commas-as-thousands-separators-in-javascript function numberWithCommas(x){ return x.toString()。replace(/ \ B(?=(\ d {3})+(?!\ d))/ g,「,」); } – wonghenry

回答

2

你試過

var some_string_value = '-10000.50'; 
parseFloat(some_string_value).toLocaleString() 

1

使用「的indexOf(‘’)」,拼接兩個部分,然後用你找到了方法。

function addComma(num){ 
 
//some type check here 
 
\t var numStr = num.toString(); 
 
\t var intEnd = numStr.indexOf('.'); 
 
var onePart =numStr,otherPart =''; 
 
if(intEnd !== -1){ 
 
\t var onePart = numStr.slice(0,intEnd); 
 
\t var otherPart = numStr.slice(intEnd); 
 
} 
 
\t 
 
\t return onePart.replace(/(\d)(?=(?:\d{3})+$)/g, '$1,')+otherPart; 
 
}

相關問題