0

I want input the digit numbers in the textbox only. Either a number or a number with two decimals. For example, 12345 or 1234.56.

I found some code online but I can't locate the resource now. That one only works for a number but fails on the two decimals. I want to modify the code. Here it is.

 currencyChars = new RegExp('[\.,]', 'g'); // we're going to remove commas and dots
constructor(public element: ElementRef, public renderer: Renderer2, private decimalPipe: 
DecimalPipe) {}

ngOnInit() {
 this.format(this.element.nativeElement.value);
}

@HostListener('input', ["$event.target.value"]) onInput(e: string) {
  this.format(e);
}

 format(val: string) {
    const numberFormat = parseInt(String(val).replace(this.currencyChars, ''));
    const usdollar = this.decimalPipe.transform(numberFormat, '1.0', 'en-US');
    this.render.setProperty(this.element.nativeElement, 'value', usdollar);
 }

I guess that I have to change the format method. Please help.

Hello
  • 796
  • 8
  • 30

2 Answers2

2

from this stackoverflow answer

We can improve the directive to take account decimals

We get the possibles decimals changing the @Input

  decimales: string = "";
  @Input()
  set mask(value: string) {
    const i = value.indexOf("d{0,");
    if (i > 0) {
      const decimales = +value.substr(i + 4, 1);
      this.decimales = "000000000".substr(0, decimales);
    }
    this.regExpr = new RegExp(value);
  }

And we add a @HostListener blur

  @HostListener("blur", ["$event"])
  blur($event) {
    if (this.decimales) {
      let item = $event.target;
      let values = item.value.split(".");
      let value =
        values.length > 1
          ? values[0] + "." + (values[1] + this.decimales).substr(0, this.decimales.length)
          : values[0] + "."+this.decimales;
      this.control.control.setValue(value, { emit: false });
    }
  }

The working demo

NOTE: Again the code is provide "as is" without warranty of any kind

Eliseo
  • 50,109
  • 4
  • 29
  • 67
0

Can you try changing parameters to decimal pipe

 ...
 const usdollar = this.decimalPipe.transform(numberFormat, '1.1-2', 'en-US');
 ...
ppgowda4
  • 418
  • 3
  • 12