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;
}
you can have it shortest as:
return Math.ceil(year/100);
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.
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));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With