numberToOrdinal conversion

Finish the function “numberToOrdinal”, which should take a number and return it as a string with the correct ordinal indicator suffix (in English). For example, “1” turns into “1st”, 2 to 2nd, 3 to 3rd and 4 to 4th. Below is my code


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

Unfortunately the code did not pass the following requirement;
1.) should handle single digits
expected ‘2st’ to equal ‘2nd’

2.) should handle larger double digits
expected ‘21th’ to equal ‘21st’

3.) should handle the largest cases
expected ‘101th’ to equal ‘101st’

Here…

function numberToOrdinal(n) {
// Finish me
return n;
}

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make easier to read.

See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.

Note: Backticks are not single quotes.

markdown_Forums

1 Like

Alright thanks, noted!

Alright thanks ArielLeslie, noted!

Try this @ Redneck…
I just concluded this same question now…

function numberToOrdinal(n) {

  if (n==0) {
    return n;
}
var j = n % 10,
    k = n % 100;
   

if (j == 1 && k != 11) {
    return n + "st";
}
if (j == 2 && k != 12) {
    return n + "nd";
}
if (j == 3 && k != 13) {
    return n + "rd";
}
return n + "th";

}

Hope to see you over there…

@flash94, your private email please?
Thanks.

tomiczilla@gmail.com