1

I want a function that takes a number and returns an english count number e.g.: 3 returns 3rd

My working solution:

function GetEnglishCount(number) {
    if ((number % 10 == 1) && (number % 100 != 11)) {
        return number + "st";
    }
    else if ((number % 10 == 2) && (number % 100 != 12)) {
        return number + "nd";
    }
    else if ((number % 10 == 3) && (number % 100 != 13)) {
        return number + "rd";
    }
    else {
        return number + "th";
    }
}

fiddle

Is there a more elegant/accurate way to do this?

Carel
  • 2,063
  • 8
  • 39
  • 65
  • See also http://codegolf.stackexchange.com/questions/4707/outputting-ordinal-numbers-1st-2nd-3rd – guest271314 May 09 '16 at 06:34
  • What's your concrete problem with this code? You call it a working solution, still you ask for a more accurate one. – TAM May 09 '16 at 06:56
  • 3
    Does one of the solutions to [*Add st, nd, rd and th (ordinal) suffix to a number*](http://stackoverflow.com/questions/13627308/add-st-nd-rd-and-th-ordinal-suffix-to-a-number) answer your question? – RobG May 09 '16 at 06:57

2 Answers2

1

You can skip the else chaining, because return ends the function and delete some parenthesis.

function GetEnglishCount(number) {
    if (number % 10 === 1 && number % 100 !== 11) {
        return number + "st";
    }
    if (number % 10 === 2 && number % 100 !== 12) {
        return number + "nd";
    }
    if (number % 10 === 3 && number % 100 !== 13) {
        return number + "rd";
    }
    return number + "th";
}
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
1

this is one way to write it:

function GetEnglishCount(number) {
  if([11,12,13].indexOf(number%100)+1)
    return 'th'
  switch(number%10){
    case 1: return  'st'
    case 2: return 'nd'
    case 3: return 'rd'
  }
  return 'th'
}

Fiddle Demo

mido
  • 24,198
  • 15
  • 92
  • 117