Issue: The function does not take into consideration digits further down, e.g. 21.344444445 rounds to 21.34 and not 21.35

I haven't listed this as a bug because I believe this is more an issue of rounding convention, and my understanding is that most conventions would return 21.34 as the correct answer (Math.round certainly does). However I'm not a mathematician so I'll leave this open for discussion amongst those more knowledgeable than me.

Thanks to Veli Pehlivanov for pointing this out. Veli has provided the following possible solution:

Code:

function roundTo(num, dec)
{
var ret = num;
var counter = 0;
var powVal = num * Math.pow(10, dec);
if(powVal / Math.round(powVal) == 1)
{
return num;
}
do
{
ret = ret * 10;
counter++;
}while(ret % 10 > 0);
while(counter> dec)
{
ret = Math.round(ret / 10);
counter--;
}
return ret / Math.pow(10, dec);
}

This apparently works precisely for up to 16 decimal digits.

## Bookmarks