Reputation: 4433
I have a Angular 2 / Typescript application string that contains number representations such as the following...
10000
10000.50
-10000
-10000.50
0
I want to add in commas after the thousand mark, for example...
10,000
10,000.50
-10,000
-10,000.50
0
What is the best way to do this?
I have tried some other answers but nothing is quite right.
For example this.value.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1,");
and this.value.toLocaleString();
don't seem to handle both the comman and decimal point.
Upvotes: 0
Views: 1458
Reputation: 33
Use "indexOf('.')",splice to two part,then use the method you found.
function addComma(num){
//some type check here
var numStr = num.toString();
var intEnd = numStr.indexOf('.');
var onePart =numStr,otherPart ='';
if(intEnd !== -1){
var onePart = numStr.slice(0,intEnd);
var otherPart = numStr.slice(intEnd);
}
return onePart.replace(/(\d)(?=(?:\d{3})+$)/g, '$1,')+otherPart;
}
Upvotes: 1
Reputation: 282
You can use a pipe, you can find a full answer to your question here: Add Comma Separated Thousands to Number Inputs in Angular2
Upvotes: 0
Reputation: 8070
Have you tried
var some_string_value = '-10000.50';
parseFloat(some_string_value).toLocaleString()
?
Upvotes: 2