Angular2 Currency Pipe change decimal separator

后端 未结 4 1140
后悔当初
后悔当初 2021-02-07 23:08

Hello angular friends,

I\'m working on an angular2 app (multiple actually). And I live in the Netherlands.

Currently I\'m formatting my currency with the followi

4条回答
  •  甜味超标
    2021-02-07 23:35

    Your problem has probably been solved some time ago, but just for reference for other Dutch developers (like myself):

    Create a custom Pipe:

    import {Pipe} from '@angular/core';
     
    @Pipe({
        name: 'currencyFormat'
    })
    export class CurrencyFormat {
        transform(value: number,
            currencySign: string = '€ ',
            decimalLength: number = 2, 
            chunkDelimiter: string = '.', 
            decimalDelimiter:string = ',',
            chunkLength: number = 3): string {
    
            value /= 100;
    
            let result = '\\d(?=(\\d{' + chunkLength + '})+' + (decimalLength > 0 ? '\\D' : '$') + ')';
            let num = value.toFixed(Math.max(0, ~~decimalLength));
    
            return currencySign+(decimalDelimiter ? num.replace('.', decimalDelimiter) : num).replace(new RegExp(result, 'g'), '$&' + chunkDelimiter);
        }
    }
    

    Now you can use:

    {{someIntegerWithCentsToBeDivided | currencyFormat}}
    

    The Pipe has already all the Dutch defaults included, but you can easily change them or use them as arguments in the template. For example:

    {{1234567 | currencyFormat:'$':2:' ':'.':3}}
    

    will give $12 345.67 as output.

提交回复
热议问题