Home Articles FAQs XREF Games Software Instant Books About Feedback Search Site-Map
irt.org logo

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

irt.org | Knowledge Base | JavaScript | Number | Q1721 [ previous next ]

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

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>

Provide feedback ...
AddThis Social Bookmark Button

Provide feedback ... AddThis Social Bookmark Button


Last Updated: 30th March 2008. Maintained by: Martin Webb and Michel Plungjan
irt.org liability, trademark, document use, privacy statement and software licensing rules apply.
Copyright © 1996-2008 irt.org, All Rights Reserved.