angular round to 2 decimal places code example
Example 1: angular pipe for 2 decimal places
{{ number | number : '1.2-2'}}
Example 2: angularjs round to 2 decimal places input
<input type="number" name="myDecimal" placeholder="Decimal" ng-model="myDecimal | number : 2" ng-pattern="/^[0-9]+(\.[0-9]{1,2})?$/" step="0.01" />
Example 3: accept 2 values after decimal in angular forms
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);
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();
}
}
}