0

Using the below code in Angular to cast the number to 2 decimal places using DecimalPipe.

constructor(private decimalPipe: DecimalPipe) {}

this.decimalPipe.transform('0','.2-2') //output 0.00

Any ideas of theTypeScript equivalent?

toPrecision(2) doesn't works the same

e.g.

var num = 2;

2.toPrecision(2)

Expected: 2.00 Actual: 2.0

Hary
  • 5,690
  • 7
  • 42
  • 79
  • 1
    can copy: https://github.com/angular/angular/blob/master/packages/common/src/i18n/format_number.ts – xdeepakv Apr 22 '20 at 14:53

1 Answers1

1

You can use javascript function toFixed(2);

If you want to round, you can use (Math.round(num * 100) / 100).toFixed(2);

Refer more at https://stackoverflow.com/a/6134070/4964569

Hien Nguyen
  • 24,551
  • 7
  • 52
  • 62