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’

What was the starting code you needed to finish? I assume the code you posted includes your changes also.

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!

Here are the knowns:

  • If the last two digits are not 11, the ending would be st if the last digit was 1.
  • If the last two digits are not 12, the ending would be nd if the last digit was 2.
  • If the last two digits are not 13, the ending would be rd if the last digit was 3.

In all other cases the ending would be th.

My algorithm assumes I will add th to the end unless one of the above cases is true. See if you can solve it using this logic.

There are other ways to solve it, but this seems simple enough as no math calculations are needed.

1 Like

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