Format numbers to Ordinals

May 28, 23

Ordinal suffix number format is a way of writing numbers that indicates their position in a sequence, such as first, second, third, etc. This format is commonly used in writing dates, ranks, and other similar contexts.

Format numbers to Ordinals - cover

In this format, the number is followed by a suffix that indicates its position in the sequence. For example, 1st, 2nd, 3rd, 4th, 5th, 6th, 7th, 8th, 9th, 10th, 11th, 12th, 13th, 14th, 15th, and so on.

One of the benefits of using ordinal suffix number format is that it helps to avoid ambiguity. For example, if you write "January 1", it could be interpreted as the first day of the year or the first of the month, whereas "January 1st" clearly indicates that it is the first day of the year.

It is important to note that the ordinal suffixes can be a bit tricky to use correctly, especially for non-native speakers of English. For example, "eleventh" and "twelfth" are spelled differently from what you might expect based on their pronunciation. However, with a bit of practice, it is easy to get the hang of this format and use it effectively in your writing. Following is a native JavaScript Code to easily format your numbers into ordinals.

const pluralRule = new Intl.PluralRules("en-US", { type: "ordinal" });

const suffixes = new Map([
["one", "st"],
["two", "nd"],
["few", "rd"],
["other", "th"],
]);

const formatOrdinals = (n: number): string => {
if (isNaN(n)) {
throw new Error("You need to pass a number value to `formatOrdinals`");
return;
}
const rule = pluralRule.select(n);
const suffix = suffixes.get(rule);
return `${n}${suffix}`;
};

formatOrdinals(0); // 0th
formatOrdinals(1); // 1st
formatOrdinals(2); // 2nd
formatOrdinals(3); // 3rd
formatOrdinals(4); // 4th
formatOrdinals('15') // 15th
formatOrdinals(1337); // 1337th
formatOrdinals("1s"); // Error: You need to pass a number value to `formatOrdinals`