Making one digit number as two digit using Angular Pipes

Viewed 2741

I wanted to make 1 look as 01 on html and similarly 11 as 11.

Can anyone please help me if there are such filters. Here is a sample demo code

2 Answers

Angular provides Decimal Pipes for these kind of situations. See a similar answer here.

<span>{{ number | number:'2.0' }}</span>

The Decimal Pipe's parameter accepts a string that represents your desired format. According to the docs, the format looks like this:

number: '{minIntegerDigits}.{minFractionDigits}-{maxFractionDigits}'

Where:

  • minIntegerDigits: The minimum number of integer digits before the decimal point. Default is 1.
  • minFractionDigits: The minimum number of digits after the decimal point. Default is 0.
  • maxFractionDigits: The maximum number of digits after the decimal point. Default is 3.

You could just use the the padStart method to add a specific character at the start of a string until it reaches a certain length.

import { Component, OnInit, Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'numberFormat'
})
export class NumberformatComponent implements PipeTransform {

  constructor() { }

   transform(n: string) {
     return n.padStart(2, '0');
   }
}
Related