JavaScript Snippet - getOrdinalFor(...)
HomeHTAJScriptJavaScriptPHP
Main Menu Home HTA JavaScript JScript PHP Examples Dynamically Creating Tables Dynamically Chaning Links Script Box Wormbites 2006 Includables ezCalendar getOrdinalFor(...) jPaq Other Libraries jQuery Prototype script.aculo.us

Mission & Code

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");
};

Parameters

  1. intNum:
    The integer that you would like to get the ordinal for.  If this is not an integer, the ordinal returned will always be "th".
  2. includeNumber:
    This parameter is optional.  If this evaluates to true, intNum will be prepended to the returned ordinal.  If this is not given or evaulates to false, the only thing returned will be the ordinal.

Example

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.");

Final Notes

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.

Related Search Results

  1. JavaScript - Dynamically Creating Tables:
    Gives an example of how to use JavaScript in conjunction with HTML and CSS to dynamically create tables.
  2. Math - Credit Card "Da Vinci Code":
    Learn about the credit card 'Da Vinci Code'.
  3. JavaScript Snippet - Get Current HTML Code:
    Learn how to access the HTML code that composes the page at this exact moment.
  4. JavaScript - GET Object Emulation:
    Learn how to emulate the GET object with JavaScript.
  5. JXtension - A Small, Yet Powerful JavaScript Library:
    JXtension is a small, yet powerful JavaScript library.