Skip to content

Instantly share code, notes, and snippets.

@tamunoibi
Created November 21, 2018 21:44
Show Gist options
  • Save tamunoibi/7836e7ea51616c52bd6d212a07c77ad9 to your computer and use it in GitHub Desktop.
Save tamunoibi/7836e7ea51616c52bd6d212a07c77ad9 to your computer and use it in GitHub Desktop.
Task
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".
For the purposes of this challenge, you may assume that the function will always be passed a non-negative integer. If the function is given 0 as an argument, it should return '0' (as a string).
To help you get started, here is an excerpt from Wikipedia's page on Ordinal Indicators:
st is used with numbers ending in 1 (e.g. 1st, pronounced first)
nd is used with numbers ending in 2 (e.g. 92nd, pronounced ninety-second)
rd is used with numbers ending in 3 (e.g. 33rd, pronounced thirty-third)
As an exception to the above rules, all the "teen" numbers ending with 11, 12 or 13 use -th (e.g. 11th, pronounced eleventh, 112th, pronounced one hundred [and] twelfth)
th is used for all other numbers (e.g. 9th, pronounced ninth).
Specification
numberToOrdinal(number)
take a number and return it as a string with the correct ordinal indicator suffix (in English)
Parameters
number: Number - The number to be converted to a string ordinal
Return Value
String - Returns a string ordinal based off of the number.
Constraints
0 ≤ number ≤ 10000
Examples
number Return Value
1 "1st"
2 "2nd"
3 "3rd"
4 "4th"
21 "21st"
@Hervera
Copy link

Hervera commented Jan 31, 2019

function numberToOrdinal(i) {
    var j = i % 10,
        k = i % 100;
  
    if(j == 0 && i == 0){
      return 0;
    }
    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";
  
}

console(numberToOrdinal(0));

console.log(numberToOrdinal(2));

console.log(numberToOrdinal(113));

console.log(numberToOrdinal(21));

console(numberToOrdinal(500));

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment