var1=anyInteger
var2=anyInteger
(Math.round(var1/var2)*var2)
What would be the syntax for JavaScripts bitshift alternative for the above?
Using integer not floating
Thank you
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
[UPDATED]
The quick answer:
var intResult = ((((var1 / var2) + 0.5) << 1) >> 1) * var2;It’s faster than the
Math.round()method provided in the question and provides the exact same values.Bit-shifting is between 10 and 20% faster from my tests. Below is some updated code that compares the two methods.
The code below has four parts: first, it creates 10,000 sets of two random integers; second, it does the round in the OP’s question, stores the value for later comparison and logs the total time of execution; third, it does an equivalent bit-shift, stored the value for later comparison, and logs the execution time; fourth, it compares the Round and Bit-shift values to find any differences. It should report no anomalies.
Note that this should work for all positive, non-zero values. If the code encounters a zero for the denominator, it will raise and error, and I’m pretty sure that negative values will not bit-shift correctly, though I’ve not tested.