Display amount as currency with fractions only whe

2020-02-16 04:23发布

问题:

I use this code to display amount:

 <td>{{transaction.amount}} {{transaction.currency}}</td>

Currently I have this output: 56030 USD

Something like:

<td [ngSwitch]="transaction.currency">
 <span *ngSwitchCase="'JPY'">/// Display 1000 JPY</span>
 <span *ngSwitchCase="'USD'">/// Display 10.00 USD</span>
 <span *ngSwitchDefault class="badge">/// Display 10.00 USD</span>
</td>

How I can add .00 based on currency?

回答1:

You can alter the way you do it now a bit to achieve what you want:

<td *ngIf='transaction.currency=="JPY"'>{{transaction.amount|number:'1.0-0'}} {{transaction.currency}}</td>

<td *ngIf='transaction.currency!=="JPY"'>{{transaction.amount|number:'1.2-2'}} {{transaction.currency}}</td>

The first pipe "|number:'1.2-2'" will format it as number, with 2 fraction after the dot, and the other section is just text from your transaction object

A bit better solution as suggested is

<td>{{ transaction.amount | currency:transaction.currency:'' }} {{ transaction.currency }}</td>

or if you don't mind the currency code on the left side you can use:

<td>{{ transaction.amount | currency:transaction.currency:'code' }}</td>


回答2:

This doesn't necessarily answer your question, but have you considered using the built in currency Pipe?

https://angular.io/api/common/CurrencyPipe



回答3:

You can do it by using the in-built currency pipe as

<td [ngSwitch]="transaction.currency">
     <span *ngSwitchCase="'JPY'">
        {{ transaction.amount | currency:'JPY':'symbol':'1.0-0'}}
     </span>
     <span *ngSwitchCase="'USD'">
        {{ transaction.amount | currency:'USD':'symbol':'1.2-2'}}
     </span>
     <span *ngSwitchDefault class="badge">
        {{ transaction.amount | currency:'USD':'symbol':'1.2-2'}}
     </span>
</td>

The last attribute to the currency pipe filter depicts the digits info in format

{minIntegerDigits}.{minFractionDigits}-{maxFractionDigits}

Here the US currency will have atleast one integer digit with minimum and maximum of 2 digits whereas Japanese currency will have no fractions



回答4:

Try to use currency filter:

<td>{{transaction.amount | currency: transaction.currency}}</td>