Appending suffix to numbers in JavaScript

JavascriptWeb DevelopmentFront End Technology

Problem

We are required to write a JavaScript function that takes in a number, num, as the first and the only argument.

The task of our function is to append ‘st’, ‘nd’, ‘rd’, ‘th’ to the number according to the following rules:

  • st is used with numbers ending in 1 (e.g. 1st, pronounced first)
  • nd is used with numbers ending in 2 (e.g. 92nd, pronounced ninety-second)
  • rd is used with numbers ending in 3 (e.g. 33rd, pronounced thirty-third)
  • As an exception to the above rules, all the "teen" numbers ending with 11, 12 or 13 use - th (e.g. 11th, pronounced eleventh, 112th, pronounced one hundred [and] twelfth)
  • th is used for all other numbers (e.g. 9th, pronounced ninth).

For example, if the input to the function is −

Input

const num = 4513;

Output

const output = '4513th';

Output Explanation

Even though 4513 ends with three, 13 is an exception case that must be appended with th

Example

Following is the code −

 Live Demo

const num = 4513;
const appendText = (num = 1) => {
   let suffix = "th";
   if (num == 0) suffix = "";
   if (num % 10 == 1 && num % 100 != 11) suffix = "st";
   if (num % 10 == 2 && num % 100 != 12) suffix = "nd";
   if (num % 10 == 3 && num % 100 != 13) suffix = "rd";

   return num + suffix;
};
console.log(appendText(num));

Output

4513th
raja
Published on 22-Apr-2021 11:27:15
Advertisements