How to tell angular (2) currency pipe to display as it is if value is a string not int or float

Aniruddha Das picture Aniruddha Das · Oct 21, 2016 · Viewed 20.4k times · Source

The currency pipe should be smart enough to handle string, float, int, etc automatically.

if passed value is string or not int or float, it should do nothing and display the passed value as it is. And only display formatted value if it is int or float.

It was happening in angularJs but not happening in angular (2)

How to tell currency pipe to escape in case its string and do currency formatting if its a decimal value. I am expecting something like below.

Example

<div>Money:{{'xxx/vv/cc' | currency:'USD':true:'1.2-2'}}</div> should display xxx/vv/cc

<div>Money: {{''11.99'' | currency:'USD':true:'1.2-2'}}</div> should display $11.99 --$ symbol included.

But its not happening. Error I am getting is caused by: Invalid argument 'Included' for pipe 'CurrencyPipe'

I think it was happening by default in angularjs but in angular2 its not happening by defalut.

Answer

BeetleJuice picture BeetleJuice · Oct 21, 2016

You can use the ternary operator a ? b : c to show b when a is truthy, but show c otherwise.

First have a function in your component that returns true when the value is a number.

component

isNumber(e) {return typeof e === 'number'}

Then use that to determine whether to send the value to the currency pipe or print it directly

template

<div>
    {{ isNumber(money) ? (money|currency:'USD':true:'1.2-2') : money }}  
</div>

live demo