Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
}
like image 951
CodeCabbie Avatar asked Feb 07 '17 09:02

CodeCabbie


People also ask

What is Intl NumberFormat?

Intl.NumberFormat.prototype.format() Getter function that formats a number according to the locale and formatting options of this Intl.NumberFormat object. Intl.NumberFormat.prototype.formatToParts() Returns an Array of objects representing the number string in parts that can be used for custom locale-aware formatting.

How do you format numbers in JavaScript?

The toFixed() method in JavaScript is used to format a number using fixed-point notation. It can be used to format a number with a specific number of digits to the right of the decimal. The toFixed() method is used with a number as shown in the above syntax using the '. ' operator.


2 Answers

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.
like image 141
Alex G. Wolff Avatar answered Oct 18 '22 10:10

Alex G. Wolff


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));
like image 34
Qwertiy Avatar answered Oct 18 '22 08:10

Qwertiy