Javascript - Định dạng một số thành một chuỗi:1st, 2nd, 3rd..

Định dạng một số thành một chuỗi:1st, 2nd, 3rd..

Viết một hàm JavaScript  Định dạng một số thành một chuỗi với hậu tố chính xác: 1st, 2nd, 3rd...

Mã nguồn:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JavaScript program to convert the letters of a given string  in alphabetical order.</title>
</head>
<script>
	humanize_format = function humanize(num) {
   if(typeof(num) == "undefined") return;
  if(num % 100 >= 11 && num % 100 <= 13)
        return num + "th";
        
        switch(num % 10) {
            case 1: return num + "st";
            case 2: return num + "nd";
            case 3: return num + "rd";
        }
        return num + "th";
    }
document.write(humanize_format()+"<br/>");  
document.write(humanize_format(1)+"<br/>");  
document.write(humanize_format(8)+"<br/>");  
document.write(humanize_format(301)+"<br/>");  
document.write(humanize_format(402)); 
</script>
<body>

</body>
</html> 

Xem ví dụ

Lưu đồ thuật toán:

Flowchart: JavaScript- Formats a number to a human-readable string



Chatbot Tư vấn Lộ trình CNTT 🤖
Chào bạn! Tôi có thể tư vấn về các lộ trình học CNTT dựa trên roadmap.w3typing.com. Hãy chọn một từ khóa dưới đây hoặc gõ câu hỏi của bạn (ví dụ: "Frontend", "Backend", "Python", "DevOps").