Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Limit input field to two decimal places - Angular 5

The code is as follows

<input type="number" class="form-control" value="" name="cost_price" #name="ngModel" [(ngModel)]="item.cost_price" placeholder="Cost Price"  />

User should not be able to type more that 2 decimal places.

For example, if the user wants to enter 21.256. He should be only allowed to enter 21.25

How to achieve this using angular 5?

like image 665
prajeesh Avatar asked Jun 06 '18 14:06

prajeesh


People also ask

How do you limit a float to two decimal places?

We will use %. 2f to limit a given floating-point number to two decimal places.

How do I limit the number of decimal places in JavaScript?

JavaScript Number toFixed() The toFixed() method converts a number to a string. The toFixed() method rounds the string to a specified number of decimals.

Can Int32 store decimals?

You can call the Parse or TryParse method to convert the string representation of an Int32 value to an Int32. The string can contain either decimal or hexadecimal digits. The following example illustrates the parse operation by using both a decimal and a hexadecimal string.

What is decimal in angular?

Angular Decimal Pipe is one of the bulit in pipe in Angular used to format decimal numbers according to the given decimal digits info and locale information.


1 Answers

First create Directive for limit the two decimal places in typescript like this:

import { Directive, ElementRef, HostListener } from '@angular/core';
@Directive({
  selector: '[appTwoDigitDecimaNumber]'
})
export class TwoDigitDecimaNumberDirective {
  private regex: RegExp = new RegExp(/^\d*\.?\d{0,2}$/g);
  private specialKeys: Array<string> = ['Backspace', 'Tab', 'End', 'Home', '-', 'ArrowLeft', 'ArrowRight', 'Del', 'Delete'];
  constructor(private el: ElementRef) {
  }
  @HostListener('keydown', ['$event'])
  onKeyDown(event: KeyboardEvent) {
    console.log(this.el.nativeElement.value);
    // Allow Backspace, tab, end, and home keys
    if (this.specialKeys.indexOf(event.key) !== -1) {
      return;
    }
    let current: string = this.el.nativeElement.value;
    const position = this.el.nativeElement.selectionStart;
    const next: string = [current.slice(0, position), event.key == 'Decimal' ? '.' : event.key, current.slice(position)].join('');
    if (next && !String(next).match(this.regex)) {
      event.preventDefault();
    }
  }
}

Inject Directive in your app.module.ts. In your html use that directive like this:

<input type="textbox" [(ngModel)]="InputValue" appTwoDigitDecimaNumber>

Here is working example in Angular 4/5/6: Limit Two decimal places number validation

Hope this will help you!!!!

like image 150
Sanoj_V Avatar answered Sep 17 '22 16:09

Sanoj_V