Home > Web Front-end > JS Tutorial > body text

JavaScript fun question: Which century is this?

黄舟
Release: 2017-02-04 15:15:46
Original
1355 people have browsed it

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
Copy after login

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;  
}
Copy after login

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)!


Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!