Search code examples
javascriptangulartypescriptecma

How to get a leading '+' for positive numbers in Intl.NumberFormat?


I'm using Intl.NumberFormat to convert a number type to a formatted string in typescript/javascript in Angular2. I want a native solution and this is ideal, but I need a leading plus sign to be included for positive numbers.

If this is not possible with Intl.NumberFormat how else might I do it natively?

@Input() amount : number;

drawLabel() {
   var formatter = new Intl.NumberFormat("en-GB",
                                         {
                                            style: "decimal",
                                            minimumFractionDigits:1
                                         });
   ...

   this.label = formatter.format(this.amount)
}

Solution

  • In 2019 you do this:

    var formatter = new Intl.NumberFormat("en-GB", { style: "decimal",  signDisplay: 'always' });
    
    console.log(formatter.format(-100.123456));
    // output -100.123
    console.log(formatter.format(100.123456));
    // output +100.123
    console.log(formatter.format(0));
    // output +0.