views:

230

answers:

1

Hi,

I have the following javascript function for rounding:

function round(val, numberdigits){

    return Math.round(val*Math.pow(10, numberdigits))/Math.pow(10, numberdigits);

}

In most of the cases, it does its job well, but in some rare cases, the returned value has one digit more, which is always a 5.

Example list of results with numberofdigits = 3:

5.329 - 5.081 - 4.271 - 3.271 - 2.1525 - 2.1375 - 2.1225 - 1.997 - 2.044 - 2.031 - 2.028

Can someone explain this? Or maybe provide me with a better rounding function which prevents this problem?

+1  A: 

You can use the built-in toFixed method on Numbers:

https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Number/toFixed

Number(val.toFixed(numberofDigits))
James Wheare
If you care for the type of the value then you need to be aware that `.toFixed` returns string so you may want to wrap it in `Number()`.
RaYell