Add currency symbol at right or left

97 views Asked by At

How to add a currency symbol at right if the input is or left is the input is $? Is there a pipe for it or something else?

That is the pipe I wrote but the user can enter letter that is what I want to avoid, or 000.

transform(value: unknown, currencySymbol: string):unknown {
    let stringValue = <string>value;

    if (!stringValue) {
      stringValue = currencySymbol + ' 0';
    }

    if (stringValue.charAt(0) === currencySymbol) {
      return currencySymbol + ' ' + stringValue.replace(currencySymbol, '').trim();
    } else 
    {
      return currencySymbol + ' ' + value;
    }
}
1

There are 1 answers

2
Konstantin On

The Angular currency pipe already does that based on locale data. In order to use it, you need to add the localize features first:

ng add @angular/localize

Then, you have to register all the locales you need in app.module.ts. Note that the register function has to be called directly (not inside the module constructor):

import { registerLocaleData } from '@angular/common';
import de from '@angular/common/locales/de';

registerLocaleData(de, 'de');

You can use the currency pipe like this:

{{ 9999.99 | currency }} <br/>
{{ 9999.99 | currency: "EUR" : "symbol" : undefined : "de" }}

Output:

$9,999.99
9.999,99 €

Remarks:

  • Notice that automatically not only the position of the currency symbol has changed, but also other things like the decimal separate (. or ,). So it makes absolutely sense to use the localize features of Angular here instead of re-inventing the wheel.
  • Your question indicates that your currency values already contains a currency symbol. You should try to refactor that. Add a separate currency selector if possible. Our you maybe could implement a separate filter that extracts the currency symbol.