## Javascript - Rounding numbers to decimal

**Tuesday, May 22, 2012**

function roundNumber(number, decimal) { return Math.round(number * Math.pow(10, decimal)) / Math.pow(10, decimal); }

### How it works

The first thing to understand is how the Math.round() function works in Javascript. The round function takes what ever number that it is given and strips off everything after the decimal point. So if you have a number like 343.12345678 it will return 343. For this example lets say you want to have 2 decimal points left for your output like 343.12. To get the decimal points that we want we need to move the decimal point over 2 spots so that they will not be removed from the round function. Each decimal place is a factor of 10. Tenths, Hundredths, Thousandths, etc.

Lets now multiply 343.12345678 by 10^2. 10 is the decimal and the 2 is how many we need to move.

You should get 34312.345678. Now if you use the round function you will get 34312 right?

So now that we have all the correct numbers we need to get the number back to the right value. 34312 is way bigger than 343.12. So we now divide 34312 by 10^2 again. The result is 343.12.

You are now able to round any number to a certain amount of decimal points.

## No comments :

## Post a Comment