2

i'm trying to make a function where you input a year, and the output return the centure that year is from. I got most of down, but somewhere in the logic i'm missing something and i'm not getting the correct values for when the year is, i.e. 2000 (20th century, and i get 21st)

My JS:

function centuryFromYear(year) {

    if (year <= 100) {
        console.log("um")
        return year * 0 + 1
    } else if (year > 100 && year <= 1000) {
        console.log("dois")
        var kek = year / 100
        var lul = Math.floor(kek)

    } else if (year > 1001) {
        console.log("tres")
        var kek = year / 100
        var lul = Math.floor(kek)
        return (lul + 1)
    }

}
Miguel
  • 305
  • 3
  • 16
  • `year * 0 + 1` is always going to be `1`. You don’t have a case for the year `1001`. There’s no reason for those `if` statements at all. You’re not returning anything for the years `101` to `1000`. This is quite a trivial problem, there are many resources on how to do this. [Rubber Duck Debug](http://rubberduckdebugging.com) your code. – Sebastian Simon Mar 19 '17 at 21:49
  • Hi there, 2000 is actually 21st century, and the answer you're getting is correct. https://en.wikipedia.org/wiki/21st_century. Quite silly, right? – daft300punk Mar 19 '17 at 21:53
  • @AbhilashSingh No, this is wrong. Read your link again: _“It **began on January 1, 2001** and will end on December 31, 2100.”_ – Sebastian Simon Mar 19 '17 at 21:55
  • @xufox Silly, me! embarassing. – daft300punk Mar 19 '17 at 21:57
  • @Xufox—tell that to everyone that celebrated the end of the millennium on 31 Dec 1999. ;-) – RobG Mar 19 '17 at 22:38

2 Answers2

5

May be this:

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


//* tests
[100,101,250, 1000, 1001, 1999, 2000, 2001].forEach(function(y) {
  console.log(y + ' year is in ' + centuryFromYear(y) + ' century');
});
br3t
  • 1,646
  • 2
  • 20
  • 27
0

Apologies for a slightly messy approach, I am sure there is possibly a more elegant approach available:
Note: negative centuries and year 0 AD do not exist on the Georgian calender

function myFunction() {
    year = 2000;
    b = year;
    if (b % 100 > 0){
      b = Math.floor((year)/100);
      b = b +1 ;
    }
    else if (b % 100 == 0){
      b = Math.floor((year)/100);
    }
    else if (b < 100 && b > 0){
      b = (Math.floor((year)/100)+1);
    }

}
Naz
  • 76
  • 5