Refer to this article: math-round-vs-hack

We have Math functions optimized.

We use `(num+0.5)|0`

instead of `Math.round()`

.

But there's a problem which make confused that when num > 2147483647, it comes out wrong results.

`function round(n) { return (n + 0.5) | 0; }; `

`round(2147483648)`

will return -2147483648

And according to wikipedia:

2147483647 in computing

The number 2,147,483,647 is also the maximum value for a 32-bit signed integer in >computing. It is therefore the maximum value for variables declared as int in many >programming languages running on popular CPUs, and the maximum possible score (or amount >of money) for many video games. The appearance of the number often reflects an error, >overflow condition, or missing value.[8] Similarly, "(214) 748-3647" is the sequence of >digits represented as a United States phone number and is the most common phone number >listed on web pages.[9] The data type time_t, used on operating systems such as Unix, is a 32-bit signed integer >counting the number of seconds since the start of the Unix epoch (midnight UTC of 1 >January 1970).[10] The latest time that can be represented this way is 03:14:07 UTC on >Tuesday, 19 January 2038 (corresponding to 2,147,483,647 seconds since the start of the >epoch), so that systems using a 32-bit time_t type are susceptible to the Year 2038 >problem.[11]

How can I handle this situation to ensure good performance?

-------------Problems Reply------------

Short answer: Use Math.round()

I would file this entire exercise under "why you should never do micro optimizations". Take a look at this fiddle: http://jsfiddle.net/toxicsyntax/a5rWm/2/

Here is some results from different browsers:

- Firefox 11: round: 185ms bit_round: 123ms (for 100000000 iterations)
- Chrome 18: round: 99ms bit_round: 96ms (for 100000000 iterations)
- IE 9: round: 227ms bit_round: 123ms (for 1000000 iterations)
- IPhone 4, Safari: round 399ms, bit_round 32ms (for 1000000 iterations)

Sure, in the best case the bitwise round function is way faster than using Math.round(), but does it really matter? Worst case Math.round() still handles several millions rounds pr. seconds without problems.

How many do you roundings do you have to do? I don't expect you would ever have to round numbers in javascript, except for displaying numbers, and even if you are displaying thousands of rounded numbers pr. second, Math.round() is still going to be fast enough for you.

*Update*

And also, regarding micro optimazations in general, be sure to check out the article from Coding Horror: http://www.codinghorror.com/blog/2009/01/the-sad-tragedy-of-micro-optimization-theater.html

Micro optimazation is very, very rarely a good idea.