Reputation: 21688
Angular currency pipe is not converting string/int to currency format if the number is in string format and there is no decimal points in the string.
suppose the amount is 12 and I want to show $12.00, if "12" is passed, its not showing but if 12.00 is passed its working properly.
//Code
import {Pipe, PipeTransform} from "@angular/core";
import {CurrencyPipe} from "@angular/common";
const _NUMBER_FORMAT_REGEXP = /^(\d+)?\.((\d+)(-(\d+))?)?$/;
@Pipe({name: 'myCurrency'})
export class MyCurrencyPipe implements PipeTransform {
constructor (private _currencyPipe: CurrencyPipe) {}
transform(value: any, currencyCode: string, symbolDisplay: boolean, digits: string): string {
if (typeof value === 'number' || _NUMBER_FORMAT_REGEXP.test(value)) {
return this._currencyPipe.transform(value, currencyCode, symbolDisplay, digits);
} else {
return value;
}
}
}
@Component({
selector: 'my-app',
template: `
<div>
<h2>Hello {{name}}</h2>
<div>{{priceNoDecimal}}</div> {{priceNoDecimal | myCurrency}}
<div>{{priceWithDecimal}}</div> {{priceWithDecimal | myCurrency}}
</div>
`,
})
export class App {
name:string;
priceWithDecimal: string;
priceNoDecimal: string;
constructor() {
this.name = 'Angular2',
this.priceNoDecimal = "12"
this.priceWithDecimal = "12.00"
}
}
@NgModule({
imports: [ BrowserModule ],
declarations: [ App , MyCurrencyPipe],
providers: [CurrencyPipe],
bootstrap: [ App ]
})
export class AppModule {}
//output
Hello Angular2
12
12
12.00
USD12.00
Upvotes: 0
Views: 1656
Reputation: 222484
The question may be unclear without the context. The pipe from the previous answer is the regex that is used in original number pipes to detect numbers in strings:
const _NUMBER_FORMAT_REGEXP = /^(\d+)?\.((\d+)(-(\d+))?)?$/;
In order for it to to closely mimic input conditioning of original currency pipe, the pipe may be changed to:
function isNumeric(value: any): boolean {
return !isNaN(value - parseFloat(value));
}
@Pipe({name: 'looseCurrency'})
export class LooseCurrencyPipe implements PipeTransform {
constructor(private _currencyPipe: CurrencyPipe) {}
transform(value: any, currencyCode: string, symbolDisplay: boolean, digits: string): string {
value = typeof value === 'string' && isNumeric(value) ? +value : value;
if (typeof value === 'number') {
return this._currencyPipe.transform(value, currencyCode, symbolDisplay, digits);
} else {
return value;
}
}
}
Where isNumeric
is a helper function that was extracted from framework internals. It should work fine with this approach.
Upvotes: 1
Reputation: 8335
If you look at the regexp that you have applied: /^(\d+)?\.((\d+)(-(\d+))?)?$/
it requires a decimal point.
The following regex makes the decimal point optional /^(\d+)?\.?((\d+)(-(\d+))?)?$/
Upvotes: 1