1

I have an input like the following:

<mat-form-field>
    <input matInput type="number" [placeholder]="'Hours' | translate"
                formControlName="Work" (blur)="calculate()" />
</mat-form-field>

Right now, the input allows unlimited decimals. I would like to only allow 2 decimals on that input. It could be done with any of the following solutions:

  • Restrict the input to 2 decimals, so that I can't insert more
  • Allow unlimited decimals and round to 2 decimals when I click another component

Is there any included feature in Angular for doing that? Otherwise, how can I create that restriction/rounding?

Example of the second option:

  1. The user enters the value 1,2582399512

  2. When the input is unfocused, the value is rounded to 1,26

Iñigo
  • 1,877
  • 7
  • 25
  • 55
  • I’d use a directive on the input element. I find it weird that angular community haven't figure out a way of sharing common directives and services. – Andrew Allen Feb 14 '20 at 09:46
  • Can you give some example input / output. My guess is that you would allow the input 1234.5678, but then round to 1234.57? – Kurt Hamilton Feb 14 '20 at 09:46
  • Yes, that is what I'm trying to achieve @KurtHamilton – Iñigo Feb 14 '20 at 09:48
  • 1
    https://stackoverflow.com/questions/58986023/need-angular-directive-digit-number-and-or-two-decimal-in-the-textbox/58991082#58991082 – Eliseo Feb 14 '20 at 09:55

1 Answers1

0

I am not sure if this solution will round up but the "step" property can help your case:

<mat-form-field>
<input matInput type="number" [placeholder]="'Hours' | translate"
            formControlName="Work" (blur)="calculate()" step=".01"/>
</mat-form-field>

This will allow to enter more values but will give error if exceeded 2 decimal places. I hope it helps.