Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

การปัดเศษและตัดทศนิยมตัวเลขใน JavaScript

JavaScript มีฟังก์ชันหลัก 2 ตัวสำหรับจัดการทศนิยม: Math.round() สำหรับปัดเศษ และ Math.trunc() สำหรับตัดทศนิยมทิ้ง

ตัวอย่างโค้ด

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Round & Trunc</title>
  <style>
    body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; }
    .result, .sample { font-size: 20px; font-weight: 500; color: blueviolet; }
    .sample { color: red; }
  </style>
</head>
<body>
  <h1>การปัดเศษและตัดทศนิยมตัวเลขใน JavaScript</h1>
  <div class="sample">3.999</div>
  <div class="result"></div>
  <br />
  <button class="Btn">คลิกที่นี่</button>
  <h3>คลิกปุ่มด้านบนเพื่อปัดเศษและตัดทศนิยมตัวเลขข้างต้น</h3>
  <script>
    const resEle = document.querySelector(".result");
    const BtnEle = document.querySelector(".Btn");
    
    BtnEle.addEventListener("click", () => {
      resEle.innerHTML = `Math.round(3.9999) = ${Math.round(3.9999)}<br>`;
      resEle.innerHTML += `Math.trunc(3.9999) = ${Math.trunc(3.9999)}<br>`;
    });
  </script>
</body>
</html>

ฟังก์ชัน Math สำหรับจัดการทศนิยม

ฟังก์ชันคำอธิบายตัวอย่างผลลัพธ์
Math.round(x)ปัดเศษเป็นจำนวนเต็มใกล้เคียง3.5, 3.4, -3.54, 3, -3
Math.trunc(x)ตัดทศนิยมทิ้ง (ทิ้งส่วนทศนิยม)3.9, -3.93, -3
Math.floor(x)ปัดลง (ไปทาง -∞)3.9, -3.13, -4
Math.ceil(x)ปัดขึ้น (ไปทาง +∞)3.1, -3.94, -3
Math.fround(x)ปัดเป็น 32-bit float1.3371.3370000123977661

ความแตกต่างสำคัญ: trunc vs floor vs ceil

Math.trunc(3.9)   // 3  (ตัดทิ้ง)
Math.floor(3.9)   // 3  (ปัดลง)
Math.ceil(3.9)    // 4  (ปัดขึ้น)

Math.trunc(-3.9)  // -3 (ตัดทิ้ง)
Math.floor(-3.9)  // -4 (ปัดลง = ไปทางลบมากขึ้น)
Math.ceil(-3.9)   // -3 (ปัดขึ้น = ไปทางบวกมากขึ้น)

ผลลัพธ์

Math.round(3.9999) = 4, Math.trunc(3.9999) = 3