
Here we are going to convert those numeral (e.g. 1, 2, 3, etc.) values to it's ordinal equivalent.
Sample and Analysis
By mathematical rule:- if a numeral ends with 1, the number is followed by "st"
- if a numeral ends with 2, the number is followed by "nd"
- if a numeral ends with 3, the number is followed by "rd"
- else, the number is followed by "th"
Thus it should look like this:
1 = 1st
2 = 2nd
11 = 11th
20 = 20th
31 = 31st
101 = 101st
The JavaScript Code
function getOrdinal(number) {
number += '';
if (number.length === 1) {
if (number === '1') return number + "st";
if (number === '2') return number + "nd";
if (number === '3') return number + "rd";
if (number != '1'&& number != '2' && number != '3') return number + "th"
}
else {
secLast = number[number.length - 2];
lastLast = number[number.length - 1];
if (secLast === '1') return number + 'th';
else {
if (lastLast === '1') return number + "st";
if (lastLast === '2') return number + "nd";
if (lastLast === '3') return number + "rd";
if (lastLast != '1' && lastLast != '2' && lastLast != '3') return number + "th"
}
}
}
ajibanda++
is a blog about programming and developing. Here, we aim to provide in-depth tutorials that teach you how to code even for beginners!
Sign up to our weekly newsletter for
FREE
tips and blog news direct to your inbox!
No comments :
Post a Comment
Thanks for dropping by and I would really appreciate if you can drop some comments..