Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
JavaScript Get English count number
We are required to write a JavaScript function that takes in a number and returns an English ordinal number for it (1st, 2nd, 3rd, 4th, etc.).
Example
3 returns 3rd 21 returns 21st 102 returns 102nd
How Ordinal Numbers Work
English ordinal numbers follow these rules:
- Numbers ending in 1: add "st" (1st, 21st, 31st) ? except 11th
- Numbers ending in 2: add "nd" (2nd, 22nd, 32nd) ? except 12th
- Numbers ending in 3: add "rd" (3rd, 23rd, 33rd) ? except 13th
- All others: add "th" (4th, 5th, 6th, 7th, 8th, 9th, 10th, 11th, 12th, 13th)
Implementation
const englishCount = num => {
if (num % 10 === 1 && num % 100 !== 11) {
return num + "st";
}
if (num % 10 === 2 && num % 100 !== 12) {
return num + "nd";
}
if (num % 10 === 3 && num % 100 !== 13) {
return num + "rd";
}
return num + "th";
};
// Test with various numbers
console.log(englishCount(1)); // 1st
console.log(englishCount(2)); // 2nd
console.log(englishCount(3)); // 3rd
console.log(englishCount(11)); // 11th (exception)
console.log(englishCount(21)); // 21st
console.log(englishCount(102)); // 102nd
console.log(englishCount(111)); // 111th (exception)
1st 2nd 3rd 11th 21st 102nd 111th
How It Works
The function checks the last digit using num % 10 and handles the special cases (11th, 12th, 13th) using num % 100:
-
num % 10gets the last digit -
num % 100gets the last two digits to handle teens (11, 12, 13) - The teens (11th, 12th, 13th) always use "th" regardless of their last digit
Alternative Implementation
const getOrdinalSuffix = num => {
const lastTwoDigits = num % 100;
const lastDigit = num % 10;
// Handle teens (11th, 12th, 13th)
if (lastTwoDigits >= 11 && lastTwoDigits num + getOrdinalSuffix(num);
console.log(englishCountV2(1)); // 1st
console.log(englishCountV2(22)); // 22nd
console.log(englishCountV2(13)); // 13th
1st 22nd 13th
Conclusion
Converting numbers to English ordinals requires handling the special cases of 11th, 12th, and 13th, while applying standard "st", "nd", "rd" rules for other numbers ending in 1, 2, or 3.
Advertisements
