This tutorial will guide you how to convert numbers to ordinal numbers in JavaScript. Getting the ordinal number of numbers allows you to display it in a human-readable format.
Key Points
What is an ordinal number?
Ordinal numbers define numbers as part of order or sequence. "First", "Second" and "Third" are all examples of ordinal numbers. When using numbers to display chart results, month dates, or rankings, you usually need to use ordinal numbers.
Numbers can be used to display many different types of data and results. When presenting numbers to users, they usually need to be rendered in a more readable format—such as adding an ordinal suffix (e.g., "June 12" instead of "June 12").
Ordinal suffix rules in English
Let's see how ordinal numbers are used in English. English ordinal numbers follow a predictable, if not very simple rules:
How to get the ordinal number of numbers?
To get the ordinal number of a number, you can use the following function:
function getOrdinal(n) { let ord = 'th'; if (n % 10 == 1 && n % 100 != 11) { ord = 'st'; } else if (n % 10 == 2 && n % 100 != 12) { ord = 'nd'; } else if (n % 10 == 3 && n % 100 != 13) { ord = 'rd'; } return ord; }
getOrdinal
The function takes a number as an argument and returns the ordinal number of that number. Since most ordinal numbers end with "th", the default value for ord
is set to th
. You then test the numbers based on different conditions and change the ordinal number if necessary.
You will notice that the remainder (%) operator is used in each condition. This operator returns the remaining value after dividing the left operand by the right operand. For example, 112 % 100 returns 12.
To test if a number should have an ordinal st, you need to check if n is one larger than a multiple of ten (n % 10 == 1, including 1 itself), but not 11 (n % 100 != 11, including 11 itself).
To test if a number should have an ordinal nd, you need to check if n is older than a multiple of ten (n % 10 == 2, including 2 itself), but not 12 (n % 100 != 12, including 12 itself).
To test if a number should have an ordinal rd, you need to check if n is three times larger than a multiple of ten (n % 10 == 3, including 3 itself), but not 13 times larger than a multiple of 100 (n % 100 != 13, including 13 itself).
If all conditions are false, the value of ord
remains at th
.
Conclusion
In this tutorial, you learned how to retrieve ordinal numbers of numbers. Ordinal numbers can be used in a variety of situations, such as displaying dates or rankings in a human-readable format.
(Subsequent content, such as the FAQ section, can be rewrite similarly based on the original text, maintaining the consistency of the content, and adjusting the sentences and expressions to make them more natural and smooth.)
The above is the detailed content of Quick Tip: How to Convert Numbers to Ordinals in JavaScript. For more information, please follow other related articles on the PHP Chinese website!