[UPDATED] Quick response:
var intResult = ((((var1 / var2) + 0.5) << 1) >> 1) * var2;
This is faster than the method Math.round()provided in the question and gives exact values.
The bit shift is 10-20% faster than my tests. Below is the updated code that compares the two methods.
: -, 10 000 ; -, , ; -, -, ; -, Round Bit-shift, - . .
, , . , , , , .
var arr1 = [],
arr2 = [],
arrFloorValues = [],
arrShiftValues = [],
intFloorTime = 0,
intShiftTime = 0,
mathround = Math.round,
i;
for (i = 0; i < 100000; i++) {
arr1.push(Math.round(Math.random() * 1000) + 1);
arr2.push(Math.round(Math.random() * 1000) + 1);
}
var intStartTime = new Date().getTime();
for (i = 0; i < arr1.length; i++) {
arrFloorValues.push(mathround(arr1[i] / arr2[i]) * arr2[i]);
}
console.log("Math.floor(): " + (new Date().getTime() - intStartTime));
var intStartTime = new Date().getTime();
for (i = 0; i < arr1.length; i++) {
arrShiftValues.push( ( ( ( (arr1[i] / arr2[i]) + 0.5) << 1 ) >> 1 ) * arr2[i]);
}
console.log("Shifting: " + (new Date().getTime() - intStartTime));
intMaxAsserts = 100;
for (i = 0; i < arr1.length; i++) {
if (arrShiftValues[i] !== arrFloorValues[i]) {
console.log("failed on",arr1[i],arr2[i],arrFloorValues[i],arrShiftValues[i])
if (intMaxAsserts-- < 0) break;
}
}