Skip to content

Instantly share code, notes, and snippets.

@JonCatmull
Last active January 12, 2024 16:09
Show Gist options
  • Save JonCatmull/da9c8bb7367f1f55a4080bbc525c09ac to your computer and use it in GitHub Desktop.
Save JonCatmull/da9c8bb7367f1f55a4080bbc525c09ac to your computer and use it in GitHub Desktop.
Appends ordinal (st, nd ,rd ,th) to number or turns number into ordinal. Typescript Angular2 Pipe
import { Pipe, PipeTransform } from '@angular/core';
const ordinals: string[] = ['th','st','nd','rd'];
/*
* Append ordinal to number (e.g. "1st" position)
* Usage:
* value | ordinal:keepNumber
* Example:
* {{ 23 | ordinal}}
* formats to: '23rd'
* Example:
* {{ 23 | ordinal:false}}
* formats to: 'rd'
*/
@Pipe({name: 'ordinal'})
export class OrdinalPipe implements PipeTransform {
transform(n: number, keepNumber: boolean = true) {
let v = n % 100;
return (keepNumber?n:'') + (ordinals[(v-20)%10]||ordinals[v]||ordinals[0]);
}
}
@battulasurendra
Copy link

Really good. Thank You

@gvdm90
Copy link

gvdm90 commented Jan 21, 2020

Great! Thank you very much

@ShaneMcGowan
Copy link

Great stuff, thanks for sharing!

@ShrinivasKattimani
Copy link

Thanks a ton man. It saved a light year for me.

@Nonamelover
Copy link

So why minus 20? What difference does it make?

@MartinNowak
Copy link

So why minus 20? What difference does it make?

1st, 2nd, 3rd, 11th, 12th, 13th, 21st, 22nd, 23rd

@a-bunting
Copy link

Great little pipe, thanks very much!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment