Display amount as currency with fractions only when currency type has fractions

后端 未结 4 1330
庸人自扰
庸人自扰 2020-12-22 12:59

I use this code to display amount:

 {{transaction.amount}} {{transaction.currency}}

Currently I have this output: 5603

相关标签:
4条回答
  • 2020-12-22 13:18

    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

    0 讨论(0)
  • 2020-12-22 13:29

    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>
    
    0 讨论(0)
  • 2020-12-22 13:33

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

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

    0 讨论(0)
  • 2020-12-22 13:34

    Try to use currency filter:

    <td>{{transaction.amount | currency: transaction.currency}}</td>
    
    0 讨论(0)
提交回复
热议问题