In: Computer Science
•Make the title of the page " Nearest Integer”. This is a rounding application.
•Assume you are given a number with values after the decimal point, such as 3.14. Is
3.14 nearest to 3 or 4? Your program should figure this out.
•You can get the lower integer of any positive floating-point value using “parseInt”. You
can get the higher integer by simply taking the lower value and adding 1.
•Determine which integer (higher or lower) is closer to your value and print that result.
•.Create these empty “div” element(s) on the screen: results
•Put one input text boxes on the screen and a button. Label the first box as “Enter the
first number.” Put a button on the screen with the text that reads “Determine the
nearest integer.”
•When the user enters a floating-point number and clicks the button, the “results” div
box should determine the nearest integer. “The nearest integer is 3.”
•To make this problem a little easier, assume that you will only be given a positive
number.
Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
body {
margin: 0px 10px;
font-family: Arial;
}
header {
background-color: cornflowerblue;
padding: 10px;
color: aliceblue;
text-align: center;
font-size: 25px;
font-weight: bold;
}
.input-area {
width: 50%;
margin: auto;
padding: 20px;
}
input {
padding: 8px;
margin-bottom: 10px;
}
button {
padding: 8px;
background-color: cornflowerblue;
color: aliceblue;
border: 2px solid darkblue;
border-radius: 4px;
cursor: pointer;
}
.results {
text-align: center;
font-size: 30px;
color: cornflowerblue;
}
</style>
<title>Nearest Integer</title>
</head>
<body>
<header>Nearest Integer</header>
<div class="input-area">
<label for="input">Enter the first number</label>
<input type="text" id="input" required>
<button onclick="getNearestInteger()">Determine the nearest integer</button>
</div>
<div class="results">
</div>
<script>
function getNearestInteger() {
// Get elements and their values
var input = document.getElementById('input').value;
var result = document.querySelector('.results');
var integer = parseInt(input); // Getting lower value
if ((input - integer) >= 0.5) {
integer = integer + 1;
}
result.innerHTML = `<b>The nearest integer is ${integer}</b>`
}
</script>
</body>
</html>
Output:
Code Screenshot: