JavaScript interesting question: What century is this?

Source: Internet
Author: User
Enter the year in numbers to return the century to which they belong. Enter the year in numbers to return the century to which they belong.

For example, in the 2016 s, there is no doubt that this is the 21st century, which we remember as 21st.

These years are 4-digit numeric strings, so you do not need to verify them.

Below are some examples:

Input: 1999 Output: 20th  Input: 2011 Output: 21st  Input: 2154 Output: 22nd  Input: 2259 Output: 23rd  Input: 1124 Output: 12th  Input: 2000 Output: 20th

First, let's take a look at how we convert the year into a century?


If you think about it, you can think of dividing the year by 100 and then rounded up to get the century.

However, there is another question: what should we do with the "st", "nd", "rd", and "th" after the century?

Take a pen, take a blank sheet of paper, and take statistics to find the rule:

In the 20th century and before, for example, tenth, eleventh, and twelfth ...... twentieth were both plus th.

After the 20th century, any century that has been divided by ten, such as twentyfirst, thirtyfirst, fortyfirst ...... it is the addition of st. For any century divided by 10 for 2, it is the addition of nd. For any century divided by 10 for 3, the addition of rd.

The other centuries after the 20th century are the plus th.

Therefore, we write the statistical logic into code:

function whatCentury(year){      var century = Math.ceil(year / 100);      if(century <= 20){          century += "th";      }      else{          if(century % 10 == 1){              century += "st";          }          else if(century % 10 == 2){              century += "nd";          }          else if(century % 10 == 3){              century += "rd";          }          else{              century += "th";          }      }      return century;  }

The above is JavaScript interesting question: Which century is this? For more information, see the PHP Chinese website (www.php1.cn )!

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.