Ordinal Number Formatting
Turn integers into 1st, 2nd, 3rd and 11th using Intl.PluralRules ordinal categories with a safe fallback.
Code
const EN_ORDINAL_SUFFIX = { one: "st", two: "nd", few: "rd", other: "th" };
export function formatOrdinal(value, locale = "en") {
if (!Number.isInteger(value)) throw new TypeError("value must be an integer");
const rules = new Intl.PluralRules(locale, { type: "ordinal" });
const suffix = locale.toLowerCase().startsWith("en")
? EN_ORDINAL_SUFFIX[rules.select(Math.abs(value))]
: "";
return suffix
? String(value) + suffix
: new Intl.NumberFormat(locale).format(value);
}
export function formatOrdinalList(values, locale = "en") {
if (!Array.isArray(values)) throw new TypeError("values must be an array");
return values.map((value) => formatOrdinal(value, locale));
}What the code does
Count the functions formatOrdinal and formatOrdinalList as the entire surface area of Ordinal Number Formatting.
Invalid states are rejected up front: it throws TypeError instead of continuing with bad data.
Applying it
Entry signature: export function formatOrdinal(value, locale = "en")
Treat formatOrdinal as the API: import it, and ignore the supporting code.
Statements that matter
return values.map((value) => formatOrdinal(value, locale));
if (!Number.isInteger(value)) throw new TypeError("value must be an integer");
if (!Array.isArray(values)) throw new TypeError("values must be an array");
Interactive Tools for This Topic
Phone Number FormatterNormalize a phone number with an optional country code into E.164, RFC 3966, and grouped national formats, with digit-count validation.Duration HumanizerTurn a number of seconds into a readable duration such as 1 day, 2 hours, 3 minutes, and show the equivalent in minutes and hours.Indentation ConverterConvert leading indentation between tabs and spaces at a chosen width, leaving inner content untouched.JSON Formatter & ValidatorFormat, beautify, and validate JSON data with configurable indentation. Instantly catches syntax errors and displays a pretty-printed tree structure.
FAQ
- Is there a failure path for bad input?
- The code refuses to continue: `TypeError` is thrown while the state is still recoverable.
- Does this work in a bare project with no dependencies file?
- Yes — a bare project runs it as-is, since nothing needs declaring. The file defines `formatOrdinal`, `formatOrdinalList` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.