what pipe do we use to round a number to a nearest dollar or integer for example 2729999.61 would be 2730000 .
Is there a way to do this on the angular template like using the number pipe ? like | number or
| number : '1.2-2'
From the docs on DecimalPipe:
The value's decimal representation is specified by the digitsInfo parameter, written in the following format:
{minIntegerDigits}.{minFractionDigits}-{maxFractionDigits}
Of great importance as well:
If the formatted value is truncated it will be rounded using the "to-nearest" method:
So, you want something like number: '1.0-0':
// In your component:
myNumber = 2729999.61;
// And then in your template:
<p>Rounded number: {{ myNumber | number: '1.0-0' }}</p>
// will output 'Rounded number: 2,730,000'
If you want to format your numbers using some other criteria, creating a pipe to do so is easy. Here's an example pipe that just uses Math.round:
import { Pipe, PipeTransform } from '#angular/core';
#Pipe({ name: 'customNumber' })
export class CustomNumberPipe implements PipeTransform {
transform(value: number, ...args: any[]) {
return Math.round(value);
}
}
... and to use it, make sure your pipe is imported as a declaration in your app module, then:
<!-- will output 'Rounded with custom pipe: 2730000' -->
<p>Rounded with custom pipe: {{ myNumber | customNumber }}</p>
Here's a working stackblitz with both options to get you going.
Related
I have a values like 54781.7622000 , 1123.11. I want this values in a format like $54781.76 , $1123.11.
//import currency pipe
import { CurrencyPipe } from '#angular/common'
//initialize in constructor
constructor(private cp: CurrencyPipe)
this.formatedOutputValue = this.cp.transform(parseInt(this.outputValue));
I have tried sum extra parameters after this value like.
this.formatedOutputValue = this.cp.transform(parseInt(this.outputValue),1.2-2);
But doesnt workout.
You are not passing all the needed parameters to the transform()
This is what the currency pipe transform() accepts in Angular (Source: Angular codebase)
transform(value: any, currencyCode?: string, display: 'code'|'symbol'|'symbol-narrow'|string|boolean = 'symbol', digitsInfo?: string, locale?: string)
You can fix your issue by passing the right data to the transform() like below.
this.formatedOutputValue = this.cp.transform(this.outputValue, 'USD', 'symbol', '1.2-2');
Here is a working example on StackBlitz. You can also see how to directly use the pipe in the template in this example.
you can do it using currency pipe only
this.cp.transform(this.data,'USD','symbol','1.2-2')
Stackblitz
You can create pipe like this:
import { Pipe, PipeTransform } from '#angular/core';
#Pipe({
name: 'formatedOutputValue'
})
export class FormatedOutputValuePipe implements PipeTransform {
transform(value: any, args?: any): any {
return value.toFixed(2).replace(/[.,]00$/, "");
}
}
In your template:
<div>{{data.value | formatedOutputValue}}</div>
You'll want to use the Currency pipe in your template like this:
{{ outputValue | currency }}
The default decimal point is 2 if a currency code is not specified.
Angular has excellent documentation on how to properly use their CurrencyPipe.
I'm working on angular 5 I want to create a custom date pipe that allows me to subtract some days from a date :
This how I display my date value :
<span>{{data.nextCertificateUpdate | date:'yyyy-MM-dd'}}</span>
for example this display a value like : 2018-08-29
I ask if it's possible to create a pipe that allow me to substract a number of days for example 28 from this date ?
Something like :
<span>{{data.nextCertificateUpdate | mypipe:28 }}</span>
and this should display value like : 2018-08-01
Thanks for any help
Adding to the nice answer given by Sachila above, you can also implement the full functionality in your custom pipe itself.
import { Pipe, PipeTransform } from '#angular/core';
import { DatePipe } from '#angular/common';
#Pipe({ name: 'mypipe' })
export class Mypipe implements PipeTransform {
// adding a default format in case you don't want to pass the format
// then 'yyyy-MM-dd' will be used
transform(date: Date | string, day: number, format: string = 'yyyy-MM-dd'): string {
date = new Date(date); // if orginal type was a string
date.setDate(date.getDate()-day);
return new DatePipe('en-US').transform(date, format);
}
}
And use your custom Pipe like:
<span>{{data.nextCertificateUpdate | mypipe: 28: 'yyyy-MM-dd'}}</span>
See a working example here: https://stackblitz.com/edit/angular-995mgb?file=src%2Fapp%2Fapp.component.html
You can create class for property like wise I have use environment class for date format DATE_FORMAT and assign by default dd-MM-yyyy format and use in date pipe.
By this approach only change the value of DATE_FORMAT and we can easily change the format of date else where.
import { Pipe, PipeTransform } from '#angular/core';
import { environment } from "../../../../environments/environment";
import { DatePipe } from "#angular/common";
#Pipe({
name: 'dateFormat'
})
export class DateFormatPipe extends DatePipe implements PipeTransform {
transform(value: any, args?: any): any {
if(Object.keys(environment).indexOf("DATE_FORMAT") >= 0){
return super.transform(value, environment.DATE_FORMAT);
}
return super.transform(value, 'dd-MM-yyyy');
}
html
<span>{{ data.date | dateFormat }}</span>
Create a custom pipe call mypipe
import { Pipe, PipeTransform } from '#angular/core';
#Pipe({ name: 'mypipe' })
export class Mypipe implements PipeTransform {
transform(date: Date, day: number): string {
date.setDate(d.getDate()-day);
return date;
}
}
call it like this
<span>{{data.nextCertificateUpdate | mypipe:28 | date:'yyyy-MM-dd'}}</span>
I have an interesting setup in my template that uses values in an array to calculate and display a number
{{moduleProps.totals | values | sum | currency:'USD':true:'1.0-0'}}
Here is the values pipe
import { Pipe, PipeTransform } from '#angular/core';
import { values } from 'lodash';
#Pipe({
name: 'values',
})
export class ValuesPipe implements PipeTransform {
transform(value: any, ...args) {
if(value){
return values(value);
}
}
}
And here is the sum pipe
import { Pipe, PipeTransform } from '#angular/core';
import { reduce } from 'lodash';
#Pipe({
name: 'sum',
})
export class SumPipe implements PipeTransform {
transform(value: any, ...args) {
if(value){
return reduce(value,(a,b)=>a+b,0);
}
}
}
The array I'm using for this looks something like this...
[donation_earnings: 868, donation_pledges: 10, raffle_purchase_earnings: 4, fixed_purchase_earnings: 6, bid_earnings: 38]
When I try to go update one of these numbers later on like this...
this.moduleProps.totals.donation_pledges += events[0].amount;
Where the events[0].amount should be a number added to whatever the current number of that object property is.
When I do this, however, the template is not updating. When I log out the object property after doing the math I see the number is changed but the template doesn't hear about it.
After I do this I am also calling
this.changeDetectorRef.detectChanges();
To help with change detection on another array of items being pushed and popped but this doesn't seem to also be picking up the changes to the values in the array.
I have also tried running this in a NgZone.run() but that wasn't updating the template either.
Is there some sort of caveat I don't understand yet about the way angular 2 handles array change detection?
EDIT:
Also when I output the individual object properties to the page I see their numbers changing, it's only the number that's passed through the pipes that isn't updating
I'm building an application using angular 2 and currency pipe, but I can't find a way to get the currency symbol according to the ISO value without any number. What I mean is that I just want the symbol without setting a number to be formatted.
Normal situation $3.00
I want only the $symbol, not the number
Angular provides an inbuilt method getCurrencySymbol which gives you currency symbol. You can write a pipe as a wrapper over that method as
import { Pipe, PipeTransform } from '#angular/core';
import { getCurrencySymbol } from '#angular/common';
#Pipe({
name: 'currencySymbol'
})
export class CurrencySymbolPipe implements PipeTransform {
transform(
code: string,
format: 'wide' | 'narrow' = 'narrow',
locale?: string
): any {
return getCurrencySymbol(code, format, locale);
}
}
and then use as:
{{'USD'| currencySymbol}} ===> $
{{'INR'| currencySymbol}} ===> ₹
Live Stackblitz Demo:
App Url: https://angular-currency-symbol-pipe.stackblitz.io
Editor Url: https://stackblitz.com/edit/angular-currency-symbol-pipe
Answered in 2017:
As I ONLY wanted the symbol for the currency, I ended up extending currency pipe with a constant number and return only the symbol. It feels sort of a "hack" to have a constant number, but as i don't want to create new currency maps and I'm not able to provide a number, i think is the easiest way.
Here is what I did:
import { Pipe, PipeTransform } from '#angular/core';
import {CurrencyPipe} from "#angular/common";
#Pipe({name: 'currencySymbol'})
export class CurrencySymbolPipe extends CurrencyPipe implements
PipeTransform {
transform(value: string): any {
let currencyValue = super.transform(0, value,true, "1.0-2");
return currencyValue.replace(/[0-9]/g, '');
}
}
Now I can use it as:
{{ 'EUR' | currencySymbol }} and get '€'
Thanks for your help and ideas!
Update:
Changed accepted answer to Varun's one as in 2020 I would use getCurrencySymbol() to accomplish that task
I know this question is quite old but just if someone happens upon it as I have, Angular has a method to do this without having to do weird and wonderful Regex and string manipulation.
I made the following pipe using the getCurrencySymbol method in #angular/common
import { Pipe, PipeTransform } from '#angular/core';
import { getCurrencySymbol } from '#angular/common';
#Pipe({
name: 'currencySymbol'
})
export class CurrencySymbolPipe implements PipeTransform {
transform(currencyCode: string, format: 'wide' | 'narrow' = 'narrow', locale?: string): any {
return getCurrencySymbol(currencyCode, format, locale);
}
}
You can use the following code in the template which avoids having to define a new pipe:
{{ ( 0 | currency : currencyCode : 'symbol-narrow' ) | slice:0:1 }}
Where this.currencyCode is set to the three digit currency symbol expected to be shown.
for example
import { Pipe, PipeTransform } from '#angular/core';
#Pipe({name: 'removeAFromString'})
export class RemoveAFromString implements PipeTransform {
transform(value: number){
return value.substring(1);
}
}
Now concat the pipes:
{{ portfolio.currentValue | currency : 'AUD' : true : '4.0' | removeAFromString}}
This is a follow-up question to Angular2 - assign pipe from a variable
What I'm looking for is a way to use a pipe based on a variable name.
I tried what Günter suggested and created a pipe that returns other pipes, but how would you return another pipe and make sure it's not rendered as text?
I have the following pipe:
import { Pipe, PipeTransform } from '#angular/core';
#Pipe({
name: 'piper'
})
export class PiperPipe implements PipeTransform {
transform(value: any, args?: any): any {
return `{{${value} | ${args}}}`;
}
}
But when I feed it with a date string and "date" argument, like this:
<!-- with e.g. obj = { value: "2016-11-08T11:11:40.000Z", pipe: "date" } -->
<div>{{obj.value | obj.pipe}}</div>
It renders it as innerText:
<div>{{2016-11-08T11:11:40.000Z | date}}</div>
I tried [innerHTML] but no luck either.