For example, you have a number 12.345. If you simply use Math.round() on it, you'll get 12. But how do you round it with a predefined decimal precision? Like, if you want to get 12.35 out of that number?

Here's how:

function roundNumber(numb:Number, decimal:Number):Number { return Math.round(numb*decimal)/decimal; } trace(roundNumber(123.456, 1)); // Output: 123 trace(roundNumber(123.456, 10)); // Output: 123.5 trace(roundNumber(123.456, 100)); // Output: 123.46 trace(roundNumber(123.456, 1000)); // Output: 123.456

Let's see how that works:

We have a number, 123.456, and we want to round it to 2 decimal places (to get 123.46). Because it is 2 decimal places - we need 2 zeros, therefore we operate with the number 100 (2 zeros in it).

First we multiply it by 100 and receive: 12345.6. Now if we round it, we get 12346. To return the comma where it belongs, we divide the number by 100 again and get 1234.6.

Simple, but effective and very useful.

We can, however, make our function a little more advanced and specify numbers after the comma to show instead of 10, 100, 1000, etc.

function roundNumber(numb:Number, decimal:Number):Number { var precision:Number = Math.pow(10,decimal); return Math.round(numb*precision )/precision; } trace(roundNumber(123.456, 0)); // Output: 123 trace(roundNumber(123.456, 1)); // Output: 123.5 trace(roundNumber(123.456, 2)); // Output: 123.46

Thanks for reading!

## 1 comment:

So useful. Thank you so much!

## Post a Comment