Math.trunc()
ต่างจาก Math.floor(), Math.ceil(), Math.round() เมธอด Math.trunc() ตัด fractional part (ส่วนทศนิยม) ทิ้ง คืนค่า integer part (ส่วนจำนวนเต็ม) เท่านั้น ไม่สนใจ rounding ไม่สนใจค่าบวก/ลบ แค่ตัดทศนิยม
รูปแบบ
Math.trunc(x);
รับตัวเลข คืนค่าหลัง truncate ส่วนทศนิยม
ตัวอย่าง: Math.trunc() ตัดทศนิยมของเลขบวก
ตัวอย่างที่ 1 (Positive Numbers)
<html> <body> <script>
var val1 = Math.trunc("1.414");
var val2 = Math.trunc("0.49");
var val3 = Math.trunc("8.9");
document.write(val1);
document.write("<br>");
document.write(val2);
document.write("<br>");
document.write(val3);
</script> </body> </html>
ผลลัพธ์
1 0 8
ตัวอย่าง: Math.trunc() ตัดทศนิยมของเลขลบ คืนค่าจำนวนเต็ม
ตัวอย่างที่ 2 (Negative Numbers)
<html> <body> <script>
var val1 = Math.trunc("-1.414");
var val2 = Math.trunc("-0.49");
var val3 = Math.trunc("-8.9");
document.write(val1);
document.write("<br>");
document.write(val2);
document.write("<br>");
document.write(val3);
</script> </body> </html>
ผลลัพธ์
-1 0 -8