Created
November 17, 2014 15:46
-
-
Save alanthai/595be15ae9db1df10da3 to your computer and use it in GitHub Desktop.
Adds ordinal suffix to an integer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// assume positive integers as parameters | |
function getDigit(n, d) { | |
return parseInt( n / Math.pow(10, d - 1), 10 ) % 10; | |
} | |
function nth(n) { | |
var d1 = getDigit(n, 1); | |
var d2 = getDigit(n, 2); | |
n = "" + n; | |
if (d1 === 1 && d2 !== 1) { | |
return n + "st"; | |
} | |
if (d1 === 2 && d2 !== 1) { | |
return n + "nd"; | |
} | |
if (d1 === 3 && d2 !== 1) { | |
return n + "rd"; | |
} | |
return n + "th"; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment