Angular 10 <input type=number> thousand separator

6.6k views Asked by At

In my Angular 10 project, I have some mat-form-fields with <input type=number> that I want to add a thousand separator to.

Meaning, as the user is entering a number, the program should insert commas every three digits and not in the floating part either.

So for example, if the user is typing 1200.5869 the user should see this number in their input field as they're typing: 1,200.5869. (which is very common in cryptocurrency trading websites by the way.)

Things I have tried so far:

  • ngx-mask library which works fine when I change the input type to tel but not when it's number.
  • writing my own angular directive that changes the input as the user is typing which I couldn't do really. because commas are not allowed in input type = number and it would just delete the input value whenever the directive tried to insert a comma.

This is my input .html code:

<mat-form-field appearance="outline">
    <mat-label>amount</mat-label>
    <input
      type="number"
      matInput
      [min]="0.1"
      [step]="0.1"
      formControlName="quantity"
    />
    <span matSuffix>
      USDT
    </span>
</mat-form-field>
2

There are 2 answers

1
Ronielo On BEST ANSWER

You have the decimal pipe (angular built-in pipe).

It should be look something like this:

{{ value_expression | number [ : digitsInfo [ : locale ] ] }}

You can have a closer look at angular API:https://angular.io/api/common/DecimalPipe

0
Shashank Raju On

I have implemented similar functionality.

I've used ControlValueAccesor to create a custom input.

It uses text input but returns a number value.

https://npmjs.com/package/ng-number-input