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 button:
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:
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 = newnumber; // Output the result to the form field (change for your purposes)
}
</script>
Use the following code for your text field and button. To change the number of decimal places, change the number 2.
<input type="text" name="numberfield" value="">
<input type="button" value="Round" onClick="roundNumber(numberfield.value, 2);">
</form>
Option 2: Using strings (beta)
This is an experimental option (published 2008-07-14) that uses a completely different approach. It is quite raw and somewhat inefficient—it will need some tweaking but it's provided in the hope that readers will let us know of any errors and possible improvements. Note that the function includes some formatting code that isn't actually necessary, it's just an extra touch to keep the decimals looking consistent.
<script type="text/javascript">
function roundNumber(number,decimals) {
var newString;// The new rounded number
decimals = Number(decimals);
if (decimals < 1) {
newString = (Math.round(number)).toString();
} else {
var numString = number.toString();
if (numString.lastIndexOf(".") == -1) {// If there is no decimal point
numString += ".";// give it one at the end
}
var cutoff = numString.lastIndexOf(".") + decimals;// The point at which to truncate the number
var d1 = Number(numString.substring(cutoff,cutoff+1));// The value of the last decimal place that we'll end up with
var d2 = Number(numString.substring(cutoff+1,cutoff+2));// The next decimal, after the last one we want
if (d2 >= 5) {// Do we need to round up at all? If not, the string will just be truncated
if (d1 == 9 && cutoff > 0) {// If the last digit is 9, find a new cutoff point
while (cutoff > 0 && (d1 == 9 || isNaN(d1))) {
if (d1 != ".") {
cutoff -= 1;
d1 = Number(numString.substring(cutoff,cutoff+1));
} else {
cutoff -= 1;
}
}
}
d1 += 1;
}
if (d1 == 10) {
numString = numString.substring(0, numString.lastIndexOf("."));
var roundedNum = Number(numString) + 1;
newString = roundedNum.toString() + '.';
} else {
newString = numString.substring(0,cutoff) + d1.toString();
}
}
if (newString.lastIndexOf(".") == -1) {// Do this again, to the new string
newString += ".";
}
var decs = (newString.substring(newString.lastIndexOf(".")+1)).length;
for(var i=0;i<decimals-decs;i++) newString += "0";
//var newNumber = Number(newString);// make it a number if you like
document.roundform.roundedfield.value = newString; // Output the result to the form field (change for your purposes)
}
Here's the form:
<table border="0" cellspacing="0" cellpadding="5">
<tr>
<td>Round:</td>
<td><input type="text" name="numberfield" value="21.3465">
to
<input name="decimalfield" type="text" value="2" size="3">
decimal places</td>
</tr>
<tr>
<td>Result:</td>
<td><input type="text" name="roundedfield" value="">
<input type="button" value="Calculate" onClick="roundNumber2(numberfield.value, decimalfield.value);">
<input type="button" value="Use a random number" onClick="randomString();"></td>
</tr>
</table>
</form>
Other Options
| toFixed() | This is another popular method, similar to Math.round. However it produces the same sort of inaccuracies. |
| Math.floor | Rounds downward to the nearest integer (e.g. 1.7 becomes 1.0). |
| Math.ceil | Rounds upward to the nearest integer (e.g. 1.3 becomes 2.0). |
Floating Point Errors
Errors occur when using Math.round and toFixed() because JavaScript's method of storing numbers is not perfect. JavaScript uses a floating-point number format which cannot store certain numbers "exactly". In other words, some numbers are approximations. This applies to all JavaScript calculations, not just rounding numbers. For example, the following equation does not provide the expected value:
alert(result);
This is why, if you need accuracy, a more complex solution is required for rounding numbers.