บทความนี้จะแสดงวิธีใช้ Math Object หาว่า floating point number ปัดเป็น nearest integer อย่างไร
เตือนใจว่าเวลาเราปัดเลข เราดูขวาของ decimal point เพื่อดูว่าเราปัดขึ้นหรือปัดลง ถ้า .5 หรือมากกว่าและเป็นบวก เราปัดขึ้น ถ้าน้อยกว่า .5 ตอนเป็นบวก เราปัดลง ในกรณีเลขลบ threshold ปรับเล็กน้อย: ถ้า .5 หรือน้อยกว่า เราปัดลง Syntax คือ:
Math.round(inputVal);
เพราะเราใช้ Math Object เริ่มจาก Math round method ตามมา parentheses เรียก method บน input value ภายใน parentheses และคืนค่าที่ปัดแล้ว
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>repl.it</title> <link href="style.css" rel="stylesheet" type="text/css" /> </head> <body> <form onsubmit=handleSubmit(event)> <label for="round">Enter a number:</label> <input id="round" onchange=handleChange(event) type="text" name="round" value=""/> <input type="submit" value="Submit" /> </form> <h3 id="root"></h3> <script> let inputVal = "" const handleChange = e => { inputVal = e.target.value; console.log(inputVal) } const handleSubmit = e => { e.preventDefault(); const root = document.querySelector("#root"); root.innerHTML = Math.round(inputVal); } const inputValue = document.getElementById("round").value </script> </body> </html>
ถ้าคุณใส่ string หรือ null เข้า input จะคืนค่า NaN ลอง code editor ด้านบนใส่ floating point numbers บางตัวเพื่อเข้าใจว่า Math.round() method ทำงานอย่างไร
สรุป
แค่นี้แหละ! คุณตอนนี้ใช้ Math object หาวิธีปัดเลขได้แล้ว นี่คือบทความช่วยคุณตัดสินใจเรียนต่ออะไร:
- JavaScript Random Number: A Complete Guide
- JavaScript ParseInt: A Step-By-Step Guide
- JavaScript Countdown Timer: A Tutorial
- JavaScript toString
- JavaScript toUpperCase and toLowerCase