7

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)
}
CodeCabbie
  • 2,136
  • 1
  • 12
  • 27

4 Answers4

8

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.
Qwertiy
  • 14,618
  • 9
  • 41
  • 96
Alex G. Wolff
  • 81
  • 1
  • 3
5

Try something like this:

class FormatterWithSign extends Intl.NumberFormat {
  constructor(...args) {
    super(...args);
  }
  
  format(x) {
    var res = super.format(x);
    return x < 0 ? res : "+" + res;
  }
}

var formatter = new FormatterWithSign("en-GB", { style: "decimal", minimumFractionDigits:1 });

console.log(formatter.format(-100.123456));
console.log(formatter.format(100.123456));
console.log(formatter.format(0));
Qwertiy
  • 14,618
  • 9
  • 41
  • 96
2

Just check if this.amount is bigger than 0. Add a leading + if that is the case.

if(this.amount > 0) this.label = "+"+formatter.format(this.amount);
else this.label = formatter.format(this.amount);

better

this.label  = formatter.format(this.amount);
if(this.amount > 0) this.label = "+"+this.label;

or in short

 this.label = this.amount > 0 ? "+"+formatter.format(this.amount): formatter.format(this.amount)
Mazz
  • 1,739
  • 21
  • 37
  • 1
    This approach doesn't do it in a localized way. For example some languages don't have the plus / minus sign at the beginning (-$123.46 in arabic is ١٢٣٫٤٦-US$). I'd consider using `Intl.NumberFormat` with a negative amount and then replacing the `-` with a `+`, but I"m not sure if every language would use a '-' as the negative character. – robmisio Nov 10 '17 at 23:58
0

You can also add Your own formatWithSign method :

Intl.NumberFormat.prototype.formatWithSign = function(x) 
{
  let y = this.format(x);
  return x < 0 ? y : '+' + y;
}

const MyFormat = new Intl.NumberFormat('en-GB', { style: "decimal", minimumFractionDigits: 2, maximumFractionDigits:2} )


console.log(MyFormat.formatWithSign(-78.123456));     // -78,12 
console.log(MyFormat.formatWithSign(90.123456));     //  +90.12
console.log(MyFormat.formatWithSign(0));            //   +0.00
Mister Jojo
  • 12,060
  • 3
  • 14
  • 33