Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting century from year

So, I have a problem where I have to return the century. I have made a code but it fails for years like 1700 or 1800. My question is, how can I make a special case that if the year is fixed, like 2000 it only divides the year by 100? I have tried with

element.slice(-2);

but it didn't work. Here's my current code

function centuryFromYear(year) {
    var x = Math.floor(year/100) + 1;
    return x; 
}
like image 259
Larica Nuvaluatidecristi Compr Avatar asked Aug 26 '18 20:08

Larica Nuvaluatidecristi Compr


3 Answers

you can have it shortest as:

return Math.ceil(year/100);
like image 105
Yakir Fitousi Avatar answered Oct 31 '22 20:10

Yakir Fitousi


Subtract 1 from year first:

function centuryFromYear(year) {
    return Math.floor((year-1)/100) + 1;
}

Examples:

centuryFromYear(1999) // 20
centuryFromYear(2000) // 20
centuryFromYear(2001) // 21

Better yet, use Math.ceil(year/100) as in Yakir's answer.

like image 36
Matt Avatar answered Oct 31 '22 21:10

Matt


Last two digits:

let myNumber = 2000;
console.log(myNumber.toString().slice(-2))

First two digits:

let myNumber = 2000;
console.log(myNumber.toString().slice(0,2))

Final function:

function 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("1901"));
console.log(centuryFromYear("2002"));
console.log(centuryFromYear(2002));
console.log(centuryFromYear(1999));
console.log(centuryFromYear(2000));
like image 34
Attersson Avatar answered Oct 31 '22 19:10

Attersson