开发者

Hard-coded 8191 10485 values in JavaScript rounding function

I've seen the following (bizarre) Javascript rounding function in some legacy code. After googling for it I can see that it crops up in a number of places online. However I can't work out why the hard-coded values 8191 and 10485 are present.

Does anyone know if there's any sensible reason why these values are included? If not, hopefully we can 开发者_高级运维kill off 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;
}


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

I'd bet this is some kind of hack to work around a perceived floating point rounding error. Floating point numbers can act in unpredictable ways, where you expect 2 but get 1.99999999973904 instead, for example, and comparisons such as >= 2 fail.


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 meant for javascript?

If you have a number (n=10449.012345)

and you want to round it to 5 decimals (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 of the non integer numbers I tried in the 8191-10485 range failed.

10000 did return 10000, so you can safely use it to round integers, I guess.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜