Limited the decimal places to 2 in mat-table

Viewed 2742

I would like to use the decimal pipe to limited the decimal numbers in my mat table. Can you please tell me how to do that?

My Table:

enter image description here

My Code:

// html
 <ng-container [matColumnDef]="column.attribute">
            <mat-header-cell id="custom-header-cell" *matHeaderCellDef>
              <div>
                {{ column.name }}
              </div>
            </mat-header-cell>
            <mat-cell id="custom-content-cell" *matCellDef="let row">
              <span class="mobile-label">{{column.mobile}}</span>
              {{ column.object !== null ? row[column.object][column.attribute] : row[column.attribute] }}
            </mat-cell>
          </ng-container>

// ts
  private monthColumns = [
    { attribute: '1', name: 'Januar', mobile: 'Januar:', object: 'values' },
    { attribute: '2', name: 'Februar', mobile: 'Februar:', object: 'values' },
    { attribute: '3', name: 'März', mobile: 'März:', object: 'values' },
    { attribute: '4', name: 'April', mobile: 'April:', object: 'values' },
    { attribute: '5', name: 'Mai', mobile: 'Mai:', object: 'values' },
    { attribute: '6', name: 'Juni', mobile: 'Juni:', object: 'values' },
    { attribute: '7', name: 'Juli', mobile: 'Juli:', object: 'values' },
    { attribute: '8', name: 'August', mobile: 'August::', object: 'values' },
    { attribute: '9', name: 'September', mobile: 'September:', object: 'values' },
    { attribute: '10', name: 'Oktober', mobile: 'Oktober:', object: 'values' },
    { attribute: '11', name: 'November', mobile: 'November:', object: 'values' },
    { attribute: '12', name: 'Dezember', mobile: 'Dezember:', object: 'values' }
  ];
1 Answers

You could use the built-in decimal pipe. Try the following

<mat-cell id="custom-content-cell" *matCellDef="let row">
  <span class="mobile-label">{{column.mobile}}</span>
  {{ column.object !== null ? row[column.object][column.attribute] : row[column.attribute] | number:'1.1-2' }}
</mat-cell>

number:'1.1-2' - Explanation

From the docs:

{minIntegerDigits}.{minFractionDigits}-{maxFractionDigits}

  • 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.

So in this case, show minimum of 1 digit before decimal point. And minimum of 1 digit and maximum of 2 digits after the decimal point.

Related