0

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
  • 1
    Do you have an example of such input value? Commented Aug 26, 2009 at 9:42

1 Answer 1

1

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)) 
Sign up to request clarification or add additional context in comments.

1 Comment

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().

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.