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

ความแตกต่างระหว่าง Math.ceil() และ Math.round() ใน JavaScript

Math.ceil() vs Math.round()

Math.ceil() - ปัดขึ้น (Ceiling)

ปัดขึ้นเป็นจำนวนเต็มที่ มากกว่าหรือเท่ากับ ค่าเดิมเสมอ

<script>
  document.write(Math.ceil(5.34));  // 6
  document.write(Math.ceil(5.00));  // 5
  document.write(Math.ceil(-5.34)); // -5 (ขึ้น = ใกล้ศูนย์)
</script>

Math.round() - ปัดตามหลักมาตรฐาน (Nearest)

ปัดเป็นจำนวนเต็มที่ ใกล้ที่สุด .5 ปัดขึ้น

<script>
  document.write(Math.round(5.34));  // 5
  document.write(Math.round(5.5));   // 6
  document.write(Math.round(-5.34)); // -5
  document.write(Math.round(-5.5));  // -5 (Note: -5.5 → -5 ไม่ใช่ -6)
</script>

ตารางเปรียบเทียบ

ค่าMath.ceil()Math.round()Math.floor()
5.34655
5.5665
5.99665
-5.34-5-5-6
-5.5-5-5-6
-5.99-5-6-6

Math.floor() - ปัดลง (Bonus)

ปัดลงเป็นจำนวนเต็มที่ น้อยกว่าหรือเท่ากับ ค่าเดิมเสมอ

สรุป

  • ceil() - ขึ้น (Ceiling)
  • floor() - ลง (Floor)
  • round() - ใกล้ที่สุด (Banker's Rounding สำหรับ .5)