Home > Article > Web Front-end > JavaScript fun question: Which century is this?
Enter some years represented by numbers and return which century they belong to.
For example, 2016 is undoubtedly the 21st century, and we record it as the 21st.
These years are all 4-digit numerical strings, so there is no need for you to verify them.
Here 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 of all, let’s observe how to convert years into centuries?
After a little thought, you can think of it, first divide the year by 100, and then round up, you can get the century it belongs to.
But, there is another question, how to get the "st", "nd", "rd", and "th" after the century?
Why don't we take a pen and a piece of white paper and make statistics, and we can find the rules:
In the 20th century and before, for example: tenth, eleventh, twelfth... The twentieth is all plus th.
After the 20th century, st is added to any century that is divisible by 10 to get 1, such as twentyfirst, thirtyfirst, fortyfirst... and st is added to any century that is divisible by 10 to get 2. For any century that is divided evenly by 10 to give 3, add rd.
In other centuries after the 20th century, th is added.
So, we wrote the logic of this statistics 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 a fun JavaScript question: Which century is this? For more related content, please pay attention to the PHP Chinese website (www.php.cn)!