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. Validation Using JavaScript:
    Learn how to do data validation with JavaScript.
  2. JavaScript - Dynamic Interaction:
    Learn how to handle events with plain JavaScript.
  3. JScript Example - Calculating 2^4194304:
    See how you can attempt to calculate an extremely large number with JScript.
  4. JavaScript - Dynamically Creating Tables:
    Gives an example of how to use JavaScript in conjunction with HTML and CSS to dynamically create tables.
  5. Indexed Page Viewer:
    Allows the user to go through web pages with a number which increases or decrease.