angular round number to 2 decimal places code example

Example 1: angular number pipe

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

//Assume someNumber = 12.221
	<!--output '12'-->
	<p>{{ someNumber | number : '1.0-0'}}</p>

//The output here is '12' because we cut the decimals off
//with the number pipe

//More examples from Angular:

	//Assume:
    //pi: number = 3.14;
  	//e: number = 2.718281828459045;

	<!--output '2.718'-->
    <p>e (no formatting): {{e | number}}</p>

    <!--output '002.71828'-->
    <p>e (3.1-5): {{e | number:'3.1-5'}}</p>

    <!--output '0,002.71828'-->
    <p>e (4.5-5): {{e | number:'4.5-5'}}</p>

    <!--output '0 002,71828'-->
    <p>e (french): {{e | number:'4.5-5':'fr'}}</p>

    <!--output '3.14'-->
    <p>pi (no formatting): {{pi | number}}</p>

    <!--output '003.14'-->
    <p>pi (3.1-5): {{pi | number:'3.1-5'}}</p>

    <!--output '003.14000'-->
    <p>pi (3.5-5): {{pi | number:'3.5-5'}}</p>

    <!--output '-3' / unlike '-2' by Math.round()-->
    <p>-2.5 (1.0-0): {{-2.5 | number:'1.0-0'}}</p>

//More information here: https://angular.io/api/common/DecimalPipe

Example 2: angular 5 convert number to two decimal in html {{}}

<div>{{ value | number:'1.2-2' }}</div>

Example 3: 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 4: 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);
    // 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();
    }
  }
}

Example 5: accept 2 values after decimal in angular forms

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

Tags:

Html Example