2017-02-15 38 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; 
 
}

相关问题