Search This Blog

Sunday, July 6, 2014

JAVASCRIPT : Add st, nd, rd and th (ordinal) suffix to a number

I would like to dynamically generate a string of text based on a current day. 
So, for example, if it is day 1 then I would like my code to generate  =  "1st".

2 = "2nd"
3 = "3rd"

I Searched And Found Good function to get ordinal suffix for number

function ordinal_suffix_of(i) {
    var j = i % 10,
        k = i % 100;
    if (j == 1 && k != 11) {
        return i + "st";
    }
    if (j == 2 && k != 12) {
        return i + "nd";
    }
    if (j == 3 && k != 13) {
        return i + "rd";
    }
    return i + "th";
}

No comments:

Post a Comment

Contact Form

Name

Email *

Message *