| JavaScript Snippet - getOrdinalFor(...) |
I was cruising the web and noticed that some people had the need to make the day of the month ordinal. For example, one may need to change the number 22 to "22nd", 13 to "13th" or 981 to "981st". The code that I found was nice but I thought that I could improve upon it a bit. Thus, the following code was born:
Number.getOrdinalFor = function(intNum, includeNumber)
{
return (includeNumber ? intNum : "") + (((intNum = Math.abs(intNum) % 100)
% 10 == 1 && intNum != 11) ? "st" : (intNum % 10 == 2 && intNum != 12)
? "nd" : (intNum % 10 == 3 && intNum != 13) ? "rd" : "th");
};
To use this code, you could do something similar to the following:
// Show the user an example of 1092 being converted to 1092nd:
alert("Here is an example: 1092" + Number.getOrdinalFor(1092));
// Here is an example which tells the user what day of the month it is:
var today = new Date();
alert("Today is the " + Number.getOrdinalFor(today.getDate(), true)
+ " day of the month.");
I think it is important to note that this code only works for integers. In addition, negative numbers have the same suffix as their positive counterparts.
Powered by jPaq.