0

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.

Ben Cameron
  • 4,335
  • 6
  • 51
  • 77
  • Did you consider using a pipe? https://angular.io/docs/ts/latest/api/common/index/CurrencyPipe-pipe.html – Saravana Feb 15 '17 at 09:00
  • Since you are using Angular2 try using DecimalPipe (either in a view or component/service). – Zyga Feb 15 '17 at 09:00
  • see this post 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 Feb 15 '17 at 09:01
  • You can also use [NumberFormat](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/NumberFormat/format) with selected locale – barbsan Feb 15 '17 at 09:03

3 Answers3

2

Have you tried

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

?

ponury-kostek
  • 7,824
  • 4
  • 23
  • 31
1

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;
}
Zhis
  • 33
  • 4
0

You can use a pipe, you can find a full answer to your question here: Add Comma Separated Thousands to Number Inputs in Angular2

Community
  • 1
  • 1
Iaconis Simone
  • 282
  • 3
  • 12