Getting century from year in JavaScript



We are required to write a JavaScript function that takes in a number or a string that represents a year. From that year our function should figure out and return the century that the year falls in.

For example −

f("2000") = 20
f(1999) = 20
f("2002") = 21

Following is the code −

Example

const centuryFromYear = year => {
   if(typeof year == 'string'){
      if(year.toString().slice(-2) == '00'){
         return year.toString().slice(0,2);
      }else{
         return (Math.floor(+year/100) +1).toString();
      };
   }else if(typeof year == 'number'){
      return Math.floor((year-1)/100) + 1;
   }else{
      return undefined;
   };
};
console.log(centuryFromYear("2000"));
console.log(centuryFromYear("2002"));
console.log(centuryFromYear(1999));

Output

Following is the output on console −

20
21
20

Advertisements