Created
December 14, 2012 01:16
-
-
Save parisminton/4281696 to your computer and use it in GitHub Desktop.
Simple JavaScript to convert a numeral to its ordinal. Values less than 10 are written as words. Values equal to 10 or greater are written with leading numerals. The optional second argument is a boolean representing whether the collection of numbers is zero-based, as in an array.
This file contains hidden or 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
function convertToOrdinal (i, zero_based) { | |
var number = zero_based ? ((i - 0) + 1) : (i - 0), // bootleg coercion | |
one = /\d+1$/, | |
two = /\d+2$/, | |
three = /\d+3$/, | |
zero_and_four_through_nine = /\d+[0456789]$/; | |
// For whatever goofy reason, typeof NaN == 'number' | |
if (typeof number == 'number' && !isNaN(number)) { | |
if (number == 0) { | |
console.log('Error: Argument cannot be zero - Zero can\'t be converted to a ranking.'); | |
} | |
else if (number == 1) { | |
return 'first'; | |
} | |
else if (number > 1 && number < 10) { | |
if (number == 2) { | |
return 'second'; | |
} | |
if (number == 3) { | |
return 'third'; | |
} | |
if (number == 4) { | |
return 'fourth'; | |
} | |
if (number == 5) { | |
return 'fifth'; | |
} | |
if (number == 6) { | |
return 'sixth'; | |
} | |
if (number == 7) { | |
return 'seventh'; | |
} | |
if (number == 8) { | |
return 'eighth'; | |
} | |
if (number == 9) { | |
return 'ninth'; | |
} | |
} | |
else if (number >= 10 && number < 20) { | |
return number + 'th'; | |
} | |
else { | |
if (one.test(number)) { | |
return number + 'st'; | |
} | |
if (two.test(number)) { | |
return number + 'nd'; | |
} | |
if (three.test(number)) { | |
return number + 'rd'; | |
} | |
if (zero_and_four_through_nine.test(number)) { | |
return number + 'th'; | |
} | |
} | |
} | |
else { | |
console.log('Error: Argument is not a number or cannot be converted to a number.'); | |
} | |
} |
Author
parisminton
commented
Dec 14, 2012
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment