Javascript - alternative to math.round

var1=anyInteger
var2=anyInteger

(Math.round(var1/var2)*var2)

What would be the syntax of the alternative for JavaScripts bitrate for the above?

Using a non-floating-point integer

thank

+3
source share
5 answers

[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, // @trinithis excellent suggestion
    i;

// Step one: create random values to compare
for (i = 0; i < 100000; i++) {
    arr1.push(Math.round(Math.random() * 1000) + 1);
    arr2.push(Math.round(Math.random() * 1000) + 1);
}

// Step two: test speed of Math.round()
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));

// Step three: test speed of bit shift
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));

// Step four: confirm that Math.round() and bit-shift produce same values
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;
    }
}
+7

, 0.5, ...

var anyNum = 3.14;
var rounded = (anyNum + 0.5) | 0;

( Math.round)

((var1/var2 + 0.5)|0) * var2

, ...

function updateAnswer() {
  var A = document.getElementById('a').value;
  var B = document.getElementById('b').value;

  var h = "Math.round(A/B) * B = <b>" + (Math.round(A/B) * B) + "</b>";
  h += "<br/>";
  h += "((A/B + 0.5)|0) * B = <b>" + ((A/B + 0.5) | 0) * B +"</b>";
  
  document.getElementById('ans').innerHTML = h;
}
*{font-family:courier}
  A: <input id="a" value="42" />
  <br/>
  B: <input id="b" value="7" />
  <br/><br/>
  <button onclick="updateAnswer()">go</button>
  <hr/>
  <span id="ans"></span>
Hide result
+4

var2 (2 ^ k),  

(var1>>k)<<k

  .

+3

(var | 0) - , . , if, Math.round .

+2

, . ?

-1
source

Source: https://habr.com/ru/post/1754339/


All Articles