JavaScript: Round to any multiple of a specific number

The Javascript Math.Round() function is used for rounding to whole numbers, or decimals:

Math.round(25.9) //returns 26
Math.round(25.2) //returns 25
Math.round(-2.58) //returns -3
Math.round(28.453*100)/100  //returns 28.45

But what if you want to round to the nearest multiple of 7? Not a problem! The solution is easier than the question sounds…

7 * Math.round(12 / 7); // returns 14
7 * Math.round(2 / 7); // returns 0

A new problem this poses is if someone enters 2, the result is 0. So lets expand on the above, making sure the lowest number we get is 7. Useful for whimsical shopping cart quantity entering. In this example we want to round to the nearest 25. The onBlur of the input element ‘amount’ fires off this function:

function RoundTo(X) {
	amount = 25 * Math.round(document.getElementById('amount').value / 25);
	if (amount == 0) {
		amount = 25;
	}
	document.getElementById('quantity').value = quantity;
}

OK great… but the customer entered a non numeric character. Also not a big deal. Simply wrap the whole thing in the numeric test “if (value == parseFloat(value))”:

function RoundTo(X) {
	if (document.getElementById('amount').value == parseFloat(document.getElementById('amount').value)) {
		amount = 25 * Math.round(document.getElementById('amount').value / 25);
		if (amount == 0) {
			amount = 25;
		}
	} else {
		amount = 25;
	}
	document.getElementById('quantity').value = quantity;
}

With that function, we have a form field where the user can enter in any number and the function will round to 25. If they enter a low number, we return 25. If they enter a non-numeric, we return 25

2 Replies to “JavaScript: Round to any multiple of a specific number”

  1. @Doug
    Sorry, this was an old post and I never updated the syntax for it. You should be able to follow along much easier now. You’d use this as with any other function: RoundTo(your_number)

Comments are closed.