-2

for example I have number : 30000 and I want to display it like this : 30 000. What should I use for it ?

More examples : 300000 -> 300 000,

3000000 -> 3000 000.

And not it's not about dots or comas, I want to recognize how many numbers there are and put space between numbers.

Angulandy2
  • 786
  • 4
  • 13
  • 31

4 Answers4

4

consider using a pipe that takes the number, convert it to a string and format it as you like.. you could add a currency two.

example:(more of a point illustration than a working code.. can't test at the moment)

//convert the string to an array
var arr = str.split("");
//back to string with added spaces
let string = "";
let count = 0;
for(i=arr.length-1; i>=0; i--){
 if(count<3){
  string =  arr[i] + string;
  count = count+1;
 }
 else{
  string = " " + string;
  count=0;
  i=i+1;
 }
}
Me1o
  • 1,629
  • 1
  • 6
  • 8
  • 1
    Can you provide an example please. – Jonathan Stellwag Nov 13 '18 at 08:41
  • 2
    @JonathanStellwag example is not necessary, because no code was given. The question was what to use for it. And a pipe is the best solution – Poul Kruijt Nov 13 '18 at 08:47
  • 2
    An example is not necessary ofc - but for the sake of a good community write 2 lines of code if you know how it works. This will improve the answer itself a lot. I previously gave this answer a upvote. Nevertheless I can ask for an example – Jonathan Stellwag Nov 13 '18 at 15:58
1

Either by using javascript as following:

function numberWithSpaces(x) {
   var parts = x.toString().split(".");
   parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, " ");
   return parts.join(".");
}
var num = numberWithSpaces(123456789);
console.log(num);

This will output 123 456 789

Edit:

Typescript:

function numberWithSpaces(x) {
  let parts = x.toString().split('.');
  parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ' ');
  return parts.join('.');
}
let num = this.numberWithSpaces(123456789);
console.log(num);

add into your typescript file (.ts) which are related to your html which contain your <h2>item.price</h2> replace num with your item.price value.

Or using pipe.

You could see example on Stackblitz

Just simply call by: element.price = format.formatCurrency(element.price);

Once you've define the helper. For your usage you could define by: <h2 *ngFor="let item of item">{{ item.price }}</h2>

Mukyuu
  • 6,436
  • 8
  • 40
  • 59
1

Make you own custom pipe: https://toddmotto.com/angular-pipes-custom-pipes

In the transform function, convert it to a string like so: Add commas or spaces to group every three digits

Rutger van Dijk
  • 330
  • 1
  • 9
0

Extremely simple way to do this:

function formatNumber(num) {
    return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79