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

เมธอด Math.abs() ใน JavaScript: ค่าสัมบูรณ์

Math.abs() - ค่าสัมบูรณ์ (Absolute Value)

ส่งคืนค่าสัมบูรณ์ของตัวเลข: ค่าบวกคงเดิม, ค่าลบกลายเป็นบวก, 0 คงเป็น 0

นิยามทางคณิตศาสตร์

|x| = {  x  if x ≥ 0
       { -x  if x < 0

ตัวอย่าง 1: ความต่างแบบสัมบูรณ์

<script>
  function myDiff(a, b) {
    return Math.abs(a - b);
  }
  document.write(myDiff(1, 9)); // 8 (ไม่ใช่ -8)
</script>

ตัวอย่าง 2: แปลงลบเป็นบวก

<html> <body> <p id="demo"></p> <script>
  document.getElementById('demo').innerHTML = Math.abs(-5.13);
</script> </body> </html>

ผลลัพธ์: 5.13

การใช้งานจริง

  • คำนวณระยะห่าง (Distance): Math.abs(x1 - x2)
  • ตรวจสอบ Tolerance: Math.abs(actual - expected) < tolerance
  • Normalize ค่าลบให้เป็นบวก

ข้อจำกัด

  • Math.abs(-2**53 - 1) อาจไม่แม่นยำ (Precision Limit)
  • ไม่รองรับ BigInt (ใช้ BigInt.prototype.abs() หรือ n < 0 ? -n : n)