How to Round Numbers in JavaScript

Important: There are two different options provided below. The first option uses the popular Math.round method which is relatively simple. Unfortunately it is not always 100% accurate due to the way JavaScript handles numbers (see below for more information). However the errors are not serious or common so this technique is acceptable for most applications. The second option is an experimental attempt to get 100% accuracy—give it a try and tell us what you think.

Option 1: Math.round()

Add the following code to the head of your HTML page:

<script language="javascript" type="text/javascript"> function roundNumber(rnum, rlength) { // Arguments: number to round, number of decimal places   var newnumber = Math.round(rnum*Math.pow(10,rlength))/Math.pow(10,rlength);   document.roundform.numberfield.value = parseFloat(newnumber); // Output the result to the form field (change for your purposes) } </script>

Read more: mediacollege.com

 

Leave a Reply

Your email address will not be published. Required fields are marked *