I am trying to display numbers within a particular table with ordinal suffixes. The table always shows three numbers which come from an XML file. The numbers show ranks, so for
I created two approaches one using Prototype, the other as a plugin :
Number.prototype.between = function(n,m){ return this > n && this < m }
Number.prototype.ORDINATE_INDEX = ["th","st","nd","rd"];
Number.prototype.toOrdinate = function(){
var
nthMod = (this % 10),
index = nthMod > 3 || this.between(10,20) ? 0 : nthMod
;
return this + this.ORDINATE_INDEX[index];
};
$(".ordinal").text(function (index, element) {
return parseInt(element).toOrdinate();
});
This is the one as a Jquery Plugin :
(function($){
var numberTool = new (function(){
var private = {};
private.ORDINATE_INDEX = ["th","st","nd","rd"];
private.parseOrdinary = function(number)
{
var
nthMod = (number % 10),
index = nthMod > 3 || private.between(number, 10,20) ? 0 : nthMod
;
return number + private.ORDINATE_INDEX[index];
}
private.between = function(number, n,m){
return number > n && number < m
}
this.isNumeric = function(number)
{
return !isNaN(parseFloat(number)) && isFinite(number);
}
this.toOrdinary = function(number)
{
return this.isNumeric(number) ? private.parseOrdinary(number) : number;
}
});
$.fn.toOrdinary = function(){
return this.each(function(){
$element = $(this);
$element.text(numberTool.toOrdinary($element.text()));
});
};
})(jQuery);
$(".ordinal").toOrdinary();
$(".ordinal").toOrdinary();
$(".ordinal").toOrdinary();
Tested on JSFIDDLE:
The prototype version example : http://jsfiddle.net/f8vQr/6/
The JQuery version example : http://jsfiddle.net/wCdKX/27/