Home Articles FAQs XREF Games Software Instant Books BBS About FOLDOC RFCs Feedback Sitemap
irt.Org
#

Q1721 How can I round up a number to the nearest 0.5?

You are here: irt.org | FAQ | JavaScript | Number | Q1721 [ previous next ]

Try the following nextNearest() function that accepts a value to round up and a number to round upto:

<html>

<head>

<script language="JavaScript"><!--
function nextNearest(value, number) {
  var ceil = Math.ceil(value);
  var remainder = value % number;
  if (remainder > 0)
    value = value - remainder + number;
  return value;
}

function doThemAll(form) {
  var output = '';
  for (var i=0; i<form.elements.length; i++) {
    if (form.elements[i].type == 'text') {
      output += form.elements[i].value + ' : ' + nextNearest(form.elements[i].value, .5) + '\n';
    }
  }
  alert(output);
}
//--></script>

</head>

<body>

<form>
<input type="text" value="0.1">
<input type="text" value="0.499">
<input type="text" value="0.501">
<input type="text" value="0.75">
<input type="text" value="1.49">
<input type="button" value="ceil" onClick="doThemAll(this.form)">
</form>

</body>

</html>

©2018 Martin Webb