Home : Internet : JavaScript : Rounding

How to Round Numbers

This page shows you how to round a number to a specified number of decimal places. The example below shows numbers being rounded to two decimal places. Enter a number (with any number of decimals) and click the Round button:

Step 1

Add the following code to the head of your HTML page. Make sure you match the NumberField variable to the form, and set the number of decimal places (if you want something other than 2 decimals).

<script language="javascript" type="text/javascript">
function roundNumber() {
	var numberField = document.roundform.numberfield; // Field where the number appears
	var rnum = numberField.value;
	var rlength = 2; // The number of decimal places to round to
	if (rnum > 8191 && rnum < 10485) {
		rnum = rnum-5000;
		var newnumber = Math.round(rnum*Math.pow(10,rlength))/Math.pow(10,rlength);
		newnumber = newnumber+5000;
	} else {
		var newnumber = Math.round(rnum*Math.pow(10,rlength))/Math.pow(10,rlength);
	}
	numberField.value = newnumber;
}
</script>

Step 2

Use the following code for your text field and button:

<form name="roundform">
<input type="text" name="numberfield">
<input type="button" value="Round" onClick="roundNumber();">
</form>


Note: In case you're wondering about the part of the function which subtracts and then adds 5000, it's a workaround for a known JavaScript bug (JavaScript can't reliably round numbers between 8192 and 10484).