Monday, May 16, 2011

Rounding Off to the “Nearest Five”

Problem:

Given a real number, write a JavaScript code to round it off to the “nearest five”. Examples:

  • 12.4 ==> 10
  • 12.6 ==> 15

Analysis:

The result would be an integer which is a multiple of 5.

Solution:

We will write the JavaScript code as part of an HTML file:

<html>

<head>

<script type=”text/javascript”>

// PART 2: the rounding off javascript code will be here

</script>

</head>

<body>

</body>

<!-- PART 1: this section will contain the HTML elements to visually display to user the transformation -->

</html>

Part 1:

We need three elements: a text box for the inputting of the number, a button to trigger the rounding off javascript code, and another text box to display the rounded off.

<input type="text" id="txtInput">

<input type="button" onClick="doRoundItOff();" value="Round It!">

<input type="text" id="txtOutput" >

Here the trigger is on the onClick event of the button which calls the doRoundItOff JavaScript function.

Part 2:

Here is the JavaScript code:

function doRoundItOff() {

var txtInput = document.getElementById("txtInput");

var txtInputValue = parseInt(txtInput.value,10);

var remainder = txtInputValue % 5;

var roundedValue = 0;

if (remainder == 2 ) {

var offsetDecimal = parseInt(txtInput.value*10,10) % 10;

if (offsetDecimal < 5)

{

roundedValue = txtInputValue - remainder;

}

else

{

roundedValue = txtInputValue - remainder + 5;

}

}

else if (remainder > 2)

{

roundedValue = txtInputValue - remainder + 5;

}

else

{

roundedValue = txtInputValue - remainder;

}

var txtOutput = document.getElementById("txtOutput");

txtOutput.value = roundedValue;

}

Explain! Explain! Explain!

We started the doRoundItOff function with identifying the txtInput HTML element. It is noteworthy to say that I usually make use as var in the JavaScript the id in the HTML element.

Next we take into account the remainder when the integer part of the input is divided by five. This remainder will determine which multiple of five we have to choose.

If the remainder is two then we take into consideration the decimal value of the input. If it is less than five then the input is closer to the largest multiple of five less than the input. Hence, we round down. Otherwise the input would be closer to the smallest multiple of five greater than the input and we round up.

If remainder is greater than two, the input is closer to the smallest multiple of five that is greater than the input. Thus, we round up. Otherwise, the input is closer to the largest multiple of five less than the input and we round down.

No comments:

Post a Comment