Reputation: 19702
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?
Upvotes: 0
Views: 1329
Reputation: 4810
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))
Upvotes: 1