Is it possible to format the number 0,00
with DecimalPipe
without specifying Locale?
I have a requirement where I've to format the number 0,00
or 0.00
regardless of the locale.
The below code throwing error saying it is not a valid number
this.decimalPipe.formatNumber('0,00', '.2-2')
I don't prefer doing this way to fix it
let num = '0,00';
num = num.replace(',','.')
this.decimalPipe.formatNumber(num, '.2-2')
As per request an implementation of a comma separated pipe, instead of going for string replacement I used the suggestion by @Igor and simply instantiate with a locale, that does use a comma as a decimal separator:
@Pipe({
name: 'commaDecimal'
})
export class CommaSeparaterDecimalPipe extends DecimalPipe {
// Use a locale which has a comma separator, don't forget to register it
transform(value: any, digitsInfo?: string, locale = 'fr'): string | null {
return super.transform(value, digitsInfo, locale);
}
}
In my opinion it is a lot cleaner, if you have a specific pipe for your use case so you have a single reference point, in case there need to be different changes in the future. If you'd rather go with string replacement after all, simply assign the return value from the super call, do the string manipulation and return the value. E.g.
let transformed = super.transform(value, digitsInfo, locale);
return `:) ${transformed}`; // using back ticks here
to render each number with a prefixed smiley.
Edit:
Seeing as in the question you only seem to use the formatNumber()
method, a pipe might not be the best solution for you seeing as the strong point of pipes is them being usable in HTML. So if you only ever call formatNumber
, you can also simply export your own function:
import {formatNumber} from '@angular/common';
export function formatCommaDecimalNumber(value: number, locale = 'en-US', digitsInfo = '.2-2'): string {
// No need to instantiate Pipes at least since Angular 8
let formatted = formatNumber(value, locale, digitsInfo);
// Handle string replacement
...
return formatted;
}
If you also need this functionality in HTML, simply create the custom pipe anyway, but call your custom formatCommaDecimalNumber
function there instead of duplicating the logic.