Hard coded 8191 10485 values ​​in JavaScript rounding function

I saw the following (bizarre) Javascript rounding function in some legacy code. After searching the Internet, I see that it appears in several places on the Internet. However, I cannot understand why the hardcoded values ​​of 8191 and 10485 are present.

Does anyone know if there is a reasonable reason why these values ​​are included? If not, I hope we can kill the meme!

function roundNumber(num,dec) { var newnumber = 0; if (num > 8191 && num < 10485) { num = num-5000; newnumber = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec); newnumber = newnumber+5000; } else { newnumber = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec); } return newnumber; } 
+6
javascript rounding magic-numbers
source share
2 answers

8191 (0x1fff) may be significant in terms of binary representation, but 10485 (0x28f5) does not seem to be.

I would argue that this is a kind of hack to get around the perceived floating point rounding error. Floating-point numbers can act in unpredictable ways where you expect 2, but instead get, for example, 1.99999999973904, and comparisons, for example, with an error> = 2.

+2
source share
 function roundNumber(num, dec){ var newnumber= 0; if(num> 8191 && num < 10485){ num= num-5000; newnumber= Math.round(num*Math.pow(10, dec))/Math.pow(10, dec); newnumber= newnumber+5000; } else{ newnumber= Math.round(num*Math.pow(10, dec))/Math.pow(10, dec); } return newnumber; } 

Are you sure this was for javascript?

If you have a number (n = 10449.012345)

and you want to round it to 5 decimal places (dec = 5), Math.round (n * Math.pow (10, dec)) / Math.pow (10, dec) returns 10449.01234.

Using roundNumber (10449.012345.5) returns 10449.012340000001, which does not seem to be an improvement. 10000.12 returned 10000.119999999999.

All non-integer numbers that I tried in the range of 8191-10485 failed.

10000 really returned 10000, so you can safely use it to round integers. I think.

+1
source share

All Articles