javascriptjqueryordinals

How to replace 1 with first, 2 with second,3 with third etc


Is there any inbuilt js/jquery function that converts 1 to first, 2 to second, 3 to third... etc.?

ex:

Num2Str(1); //returns first;
Num2str(2); //returns second;

I dont want to write a function for 100 numbers. Please help.


Solution

  • There is no inbuilt function for it.

    I did write one for up to 99:

    var special = ['zeroth','first', 'second', 'third', 'fourth', 'fifth', 'sixth', 'seventh', 'eighth', 'ninth', 'tenth', 'eleventh', 'twelfth', 'thirteenth', 'fourteenth', 'fifteenth', 'sixteenth', 'seventeenth', 'eighteenth', 'nineteenth'];
    var deca = ['twent', 'thirt', 'fort', 'fift', 'sixt', 'sevent', 'eight', 'ninet'];
    
    function stringifyNumber(n) {
      if (n < 20) return special[n];
      if (n%10 === 0) return deca[Math.floor(n/10)-2] + 'ieth';
      return deca[Math.floor(n/10)-2] + 'y-' + special[n%10];
    }
    
    // TEST LOOP SHOWING RESULTS
    for (var i=0; i<100; i++) console.log(stringifyNumber(i));
    

    DEMO: http://jsbin.com/AqetiNOt/1/edit