Skip to content

Instantly share code, notes, and snippets.

@alanthai
Created November 17, 2014 15:46
Show Gist options
  • Save alanthai/595be15ae9db1df10da3 to your computer and use it in GitHub Desktop.
Save alanthai/595be15ae9db1df10da3 to your computer and use it in GitHub Desktop.
Adds ordinal suffix to an integer
// 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