Angular

Creating a Short Number Format Pipe Using Angular

In this blog, we will learn how to improve readability. instead of displaying full numbers very often, there is a need to display shortened numbers. Here is an example of how to create your own customizable short number pipe in Angular.

What Are Pipes?

Pipe in Angular is a data processing element that is used in a presentation layer (in a template). All pipes must implement the PipeTransform interface. PipeTransform interface contains a method called “transform()” which is invoked by Angular with a value passed as a first argument and optional parameters as a second argument.

Pipes can be joined into a set of pipes. In such a case output of the previous pipe will be input for the next one.

Let’s Start,

Create a Custom Pipe

Task: Display text “1.5M” instead of 1500000 in the view.

A command to generate a new shortNumber” pipe in pipes/ directory:

ng generate pipe pipes/shortNumber

The above command creates the pipes/short-number.pipe.ts file and registers ShortNumberPipe in modules declarations.

// short-number.pipe.ts
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
  name: 'shortNumber'
})
export class ShortNumberPipe implements PipeTransform {
  transform(value: any, args?: any): any {
    return null;
  }
}

ShortNumberPipe class must implement the PipeTransform interface which is a common interface for all Angular pipes.

PipeTransform interface requires a single transform() method to be implemented. See short number functionality implementation below.

transform(number: number, args?: any): any {
    if (isNaN(number)) return null; // will only work value is a number
    if (number === null) return null;
    if (number === 0) return null;
    let abs = Math.abs(number);
    const rounder = Math.pow(10, 1);
    const isNegative = number < 0; // will also work for Negetive numbers
    let key = '';

    const powers = [
      { key: 'Q', value: Math.pow(10, 15) },
      { key: 'T', value: Math.pow(10, 12) },
      { key: 'B', value: Math.pow(10, 9) },
      { key: 'M', value: Math.pow(10, 6) },
      { key: 'K', value: 1000 }
    ];

    for (let i = 0; i < powers.length; i++) {
      let reduced = abs / powers[i].value;
      reduced = Math.round(reduced * rounder) / rounder;
      if (reduced >= 1) {
        abs = reduced;
        key = powers[i].key;
        break;
      }
    }
    return (isNegative ? '-' : '') + abs + key;
 }

In the example above code “Q” stands for quadrillion, “T” — trillion, “B” — billion, “M” — million, “k” — kilo. And hardcoded fractionize defines the precision of rounding numbers. You are welcome to adjust it as your needs.

Import Pipe

Import this pipe into the module.

@NgModule({
  declarations: [
    ShortNumberPipe
  ],
  imports: [
    CommonModule
  ],
  exports: [ShortNumberPipe]
})
export class SharedModule { }

Test Usage

Let’s check the result with this piece of HTML:

<h1>{{1500000 | shortNumber}}</h1>

After interpolation it displays 1.5M. And if substitute 1500000 with 15300 the result of number transformation will be 15.3k.

I hope you guys understand how we can do this. Let me know if you’re facing any difficulties.

You can read my previous blog here.

The source code for this tutorial is available at the github repository.

Happy Coding {;}

Nayan Raval

Nayan Raval is a MEAN Stack .Net Developer has extensive experience with designing and developing enterprise-scale applications. Key Areas Of Expertise: • ASP.NET Core MVC • ASP.NET Core Web API • C# • ASP.NET MVC 5 • Angular All versions • HTML5 • CSS3 / SCSS • Bootstrap • JavaScript • Azure • JQuery Databases and related • Microsoft SQL server MSSQL • PostgreSQL • Entity Framework (EF) • LINQ UI Frameworks • Kendo UI • Telerik • JQuery UI • Prime NG and Material UI API Integration • SignalR • DateDog • Twilio Voice Call And Message • Stripe • SendGrid (Email Camping) • Checkr • Zoom Video Call • Auth0 • Elastic Search • Quartz - Scheduler • JWT Token • Google Calendar

Recent Posts

Testing hk

Testing

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

Operation

Testing

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

TETS NEW

test

3 years ago