This article will show you how to use the Math Object to figure out how a floating point number rounds to the nearest integer.
As a reminder, when we round a number, we look to the right of the decimal point to figure out if we round up or round down. If it’s .5 or more and positive, we round up; if it’s less than .5 when positive, we round down. In the case of negative numbers, the threshold is adjusted slightly: if .5 or less, we round down. Here’s the syntax:
Math.round(inputVal);
Since we are using the Math Object, we start with Math. The round method comes next. The set of parentheses invokes the method on the input value inside the parentheses and returns the rounded value.
<!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>
If you were to enter a string or null into the input, it returns NaN.Try the code editor above and input some floating point numbers to get an idea of how the Math.round() method works.
Conclusion
That’s it! You can now use the Math object to figure out how to round a number. Here’s some articles that can help you figure out what to learn next:
About us: Career Karma is a platform designed to help job seekers find, research, and connect with job training programs to advance their careers. Learn about the CK publication.