I have already talked about a JavaScript function that rounds To the nearest number, but this was only useful if the number needed to be to the nearest 10 (or factor of). The following function is similar, but will round the number to the nearest 5 or 10, depending which is closer.
function round5(x)
{
return (x % 5) >= 2.5 ? parseInt(x / 5) * 5 + 5 : parseInt(x / 5) * 5;
}
Use the function like this:
alert(round5(12)); // returns 10
alert(round5(14)); // returns 15
The JavaScript Math.round() function will round a decimal to the nearest whole number, but I found that I needed was to round a number to the nearest 10. So after a bit of thinking I realised that I could divide the value by 10, round it using the round() function and then multiply the result by 10.
So taking it a step further I decided to create a function that would round a number to the nearest 10, 100, 1000 or whatever value is entered. If this value is less than 0 then do the reverse by multiplying and dividing the number by the given value of accuracy. Here is the function.
function roundNearest(num, acc){
if ( acc < 0 ) {
num *= acc;
num = Math.round(num);
num /= acc;
return num;
} else {
num /= acc;
num = Math.round(num);
num *= acc;
return num;
}
}
Here are some tests of the function.
alert( roundNearest(12345, 1000) ); // 1200
alert( roundNearest(12345.1234, -100) ); //12345.12
This function can be simplified a little by putting all of the calculations onto one line.
function roundNearest(num, acc){
if ( acc < 0 ) {
return Math.round(num*acc)/acc;
} else {
return Math.round(num/acc)*acc;
}
}
Recent Comments