# Round Numbers Accurately to Specified Place Value with Javascript

This function rounds numbers to a specified accuracy. The reason this is needed is Javascript's native round function only rounds to the nearest integer. In order to round to decimal places the number must be multiplied by some multiple of 10, then rounded, then divided by the same factor of 10 to get a rounded number to specified decimal places. The problem with this method is a rounding error is introduced, often producing a result such as 3.140000001 when attempting to round to two decimal places.

The function below solves this problem with one line of code.

function round(value, decimals) { return Number(Math.round(value+'e'+decimals)+'e-'+decimals); }

### Example:

**javascript**

var n = round(3.14159, 2);

**Produces the result:** 3.14