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)
}
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.
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.
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.
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With