问题
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 following:
{{someIntegerWithCentsToBeDivided / 100 | currency:'EUR':true:'1.0-2'}}
This displays something like 500 to be Eurosign 5 and 501 to be Eurosign 5.01.
Now we dutchies really like comma's the other way around so does anyone know how to change the . to a ,?
Bonus points if someone knows how to show 5,- optionally when there is no cents. My thoughts now would be to extend the CurrencyPipe
回答1:
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.
回答2:
I'm too late but I found a solution.
I'm just create a pipe to replace anything:
import { PipeTransform, Injectable, Pipe } from '@angular/core';
@Pipe({
name: 'replace'
})
@Injectable()
export class ReplacePipe implements PipeTransform {
constructor(){}
transform(item: any, replace, replacement): any {
if(item == null) return "";
item = item.replace(replace, replacement);
return item;
}
}
I used that twice to solve your case.
{{ 5.01999 | currency:'BRL':true | replace:'.':',' | replace:',00':',-' }}}
来源:https://stackoverflow.com/questions/36858634/angular2-currency-pipe-change-decimal-separator