Angular Pipes are a way to transform the format of output data for display. The data can be strings, currency amounts, dates, etc. In this article, we will learn How to Limit to 2 decimal places with a Simple Pipe.
Steps for Installing & Configuring the Angular Application
Step 1: Create an Angular application using the following command.
ng new appname
Step 2: After creating your project folder i.e. appname, move to it using the following command.
cd appname
Step 3: Create a pipe; src/app
ng generate pipe geek
Project Structure
It will look like the following
Example 1: In this example, we will Limit to 2 decimal places with a simple pipe in Angular.
<!-- app.component.html --> < h2 style = "color: green" >
GeeksforGeeks
</ h2 >
< h2 >
Limit to 2 decimal places with a simple pipe
</ h2 >
Original number: {{num}} < br >
Round off: < b style = "color: tomato;" >
{{num | number : '1.2-2'}}
</ b >
|
// app.component.ts import { Component, OnInit } from '@angular/core' ;
import { KeyValue } from '@angular/common' ;
import { Pipe, PipeTransform } from '@angular/core' ;
@Component({ selector: 'app-root' ,
templateUrl: "./app.component.html" ,
styleUrls: [ './app.component.css' ]
}) export class AppComponent { num = 1.23455
} |
// app.module.ts import { NgModule } from '@angular/core' ;
import { BrowserModule } from '@angular/platform-browser' ;
import { HttpClientModule } from '@angular/common/http' ;
import { AppComponent } from './app.component' ;
@NgModule({ declarations: [
AppComponent
],
imports: [
BrowserModule,
HttpClientModule,
],
providers: [],
bootstrap: [AppComponent]
}) export class AppModule { } |
Output:
Example 2: In this example, we will learn how to Limit to 2 decimal places with a custom pipe ‘geek’ in Angular.
<!-- app.component.html --> < h2 style = "color: green" >GeeksforGeeks</ h2 >
< h2 >Limit to 2 decimal places with a simple pipe</ h2 >
Original number: {{num}} < br >
Round off: < b style = "color: tomato;" >
{{num | geek }}
</ b >
|
// app.component.ts import { Component, OnInit } from '@angular/core' ;
import { KeyValue } from '@angular/common' ;
import { Pipe, PipeTransform } from '@angular/core' ;
@Component({ selector: 'app-root' ,
templateUrl: "./app.component.html" ,
styleUrls: [ './app.component.css' ]
}) export class AppComponent { num = 1.644666;
} |
// app.module.ts import { NgModule } from '@angular/core' ;
import { BrowserModule } from '@angular/platform-browser' ;
import { HttpClientModule } from '@angular/common/http' ;
import { AppComponent } from './app.component' ;
import { GeekPipe } from './geek.pipe' ;
@NgModule({ declarations: [
AppComponent,
GeekPipe
],
imports: [
BrowserModule,
HttpClientModule,
],
providers: [],
bootstrap: [AppComponent]
}) export class AppModule { } |
// geek.pipe.ts import { Pipe, PipeTransform } from '@angular/core' ;
@Pipe({ name: 'geek'
}) export class GeekPipe implements PipeTransform { transform(value: any) {
return value.toFixed(2)
}
} |
Output: