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.