Now Available in YourJS

When dealing with numbers, at times for presentation’s sake, we need to add ordinals to numbers. For example, instead of today is the “September 28”, you may want to say that it is the “28th of September”. I wrote the following code snippet to easily add the ordinal for any integer in JavaScript:

(function(o) {
Number.getOrdinalFor = function(intNum, includeNumber) {
return (includeNumber ? intNum : "")
+ (o[((intNum = Math.abs(intNum % 100)) - 20) % 10] || o[intNum] || "th");
};
})([,"st","nd","rd"]);

## Description

Gets the appropriate ordinal (“st”, “nd”, “rd”, or “th”) for the specified integer.

## Parameters

**intNum:**

The number for which the ordinal will be produced.
**includeNumber:**

The value that is evaluated as a boolean to determine whether or not to include the specified integer in the returned string. This is optional and thusly defaults to `false`

.

## Returns

The string containing the ordinal for the specified integer. If the second parameter evaluates to `true`

, the specified number will returned with the ordinal appended to it.

## Examples

The following shows how you could call this function:

var num1 = 1,
num2 = 12,
num3 = 123,
num4 = 1432;
var str1 = Number.getOrdinalFor(num1, true), // 1st
str2 = Number.getOrdinalFor(num2, true), // 12th
str3 = Number.getOrdinalFor(num3, true), // 123rd
str4 = Number.getOrdinalFor(num4, true); // 1432nd

You could even get a little fancy and run this on all of the numbers in a string by doing something like the following:

var str = "1, 2, and 3 place will get medals while 4 and later will get Cinnabons.";
alert(str.replace(/(\d+)/g, Number.getOrdinalFor));

The reason the above example works is because the first parameter that is passed into the function is the entire match, which in this case is the number found. The second parameter passed is the exact same thing, which since it is a string of one or more characters, will always evaluate to `true`

. Having these two circumstances in mind, in every case that a number is found, the same number with the appropriate ordinal is replaces the number in the string.

You could modify it a bit to make it work with any numbers by doing something like this:

var str = "1, 2, 3, 4.5, 6, and 7.8 are all numbers.";
alert(str.replace(/\d*\.\d+|(\d+)/g, function(match, int) {
return int
? Number.getOrdinalFor(parseInt(int, 10), 1)
: match;
}));

I will not go into detail and explain why the above works. If you don’t understand it, I suggest, if you want to become really proficient in the language, that you dissect the code. Many times, if we try things out ourselves, we will be more likely to remember and understand why something works and when we can use something like that again. Of course, if you do get to a point where you just don’t understand something, leave a comment below and I will help you out. Have fun!!!