'Displaying a number in Indian format using angular 2

I want to print numbers with commas as thousands, lacs, crores separators. for e.g:

     10,000 - ten thousand
   1,00,000 - 1 lakh
  10,00,000 - 10 lakh
1,00,00,000 - 1 crore

I have used angular's number pipe to implement comma separated values but not getting proper output it displays like this 1,000,000 - 10 lakh.

How can i implement above functionality using angular/javascript or is there any pipe for this in angular?



Solution 1:[1]

You can use .toLocalString()

The toLocaleString() method returns a string with a language-sensitive representation of this number.

var tenK= 10000;
var oneL = 100000;
var tenL = 1000000;
var oneCr = 10000000;
console.log(tenK.toLocaleString('en-IN'));
console.log(oneL.toLocaleString('en-IN'));
console.log(tenL.toLocaleString('en-IN'));
console.log(oneCr.toLocaleString('en-IN'));

Solution 2:[2]

You can do it with toLocaleString()

In localeString you need to provide locales in this case you need to use en-IN

let num1 = 1000;
let num2 = 10000;
let num3 = 1000000;

console.log(num1.toLocaleString('en-IN'));
console.log(num2.toLocaleString('en-IN'));
console.log(num3.toLocaleString('en-IN'));

Solution 3:[3]

You can also do this with regular expressions like this in Javascript:

formatNumber = (num)=>{
    return num.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
var formattedNumber = formatNumber(10000000);
console.log(formattedNumber);

Solution 4:[4]

I hope you have used pipe in correct way,

but just to confirm we can use currency pipe like

 {{price|currency:'INR':true}}

here is a skeleton syntax for currency by angular

{{ value_expression | currency [ : currencyCode [ : display [ : digitsInfo [ : locale ] ] ] ] }}

Solution 5:[5]

Here is my implementation to achieve this

Create an custom pipe:

import {Inject, Pipe, PipeTransform} from '@angular/core';

@Pipe({
  name: 'currencyFormat'
})
export class CurrencyFormatPipe implements PipeTransform {
  constructor() {
  }

  transform(value: any, ...args: any[]): any {
    if (value === undefined || value === null) {
      return '';
    }
    return new Intl.NumberFormat('en-IN', { style: 'currency', currency: 'INR' }).format(value);
  }

}

use this pipe in you template to get output in Indian format.

Please checkout Intl.NumberFormat documentation here to understand the parameters.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Prasad Telkikar
Solution 2
Solution 3 Zunnurain Badar
Solution 4 Hrishikesh Kale
Solution 5 Manish