ProblemYou want to round a number to the nearest integer, decimal place, or interval (such as to the nearest multiple of five). SolutionUse Math.round( ) to round a number to the nearest integer. Use Math.floor( ) and Math.ceil( ) to round a number down or up. Use a custom NumberUtilities.round( ) method to round a number to a specified number of decimal places or to a specified multiple. DiscussionThere are numerous reasons to round numbers. For example, when displaying the results of a calculation, you might display only the intended precision. Because all arithmetic in ActionScript is performed with floating-point numbers, some calculations result in unexpected floating-point numbers that must be rounded. For example, the result of a calculation may be 3.9999999 in practice, even though it should be 4.0 in theory. The Math.round( ) method returns the nearest integer value of any parameter passed to it: trace(Math.round(204.499)); // Displays: 204 trace(Math.round(401.5)); // Displays: 402 The Math.floor( ) method rounds down, and the Math.ceil( ) method rounds up: trace(Math.floor(204.99)); // Displays: 204 trace(Math.ceil(401.01)); // Displays: 402 To round a number to the nearest decimal place:
For example, to round 90.337 to two decimal places, you could use: trace (Math.round(90.337 / .01) * .01); // Displays: 9.34 You can use the identical math to round a number to the nearest multiple of an integer. For example, this rounds 92.5 to the nearest multiple of 5: trace (Math.round(92.5 / 5) * 5); // Displays: 95 As another example, this rounds 92.5 to the nearest multiple of 10: trace (Math.round(92.5 / 10) * 10); // Displays: 90 In practice you are likely to find it is much simpler to use a custom NumberUtilities.round( ) method that encapsulates this functionality. The custom method takes two parameters:
The NumberUtilities class is in the ascb.util package, so the first thing you'll want to add to any file that uses the class is an import statement. Here is an example of how to use the NumberUtilities.round( ) method (the following code assumes that you've imported ascb.util.NumberUtilities): trace(NumberUtilities.round(Math.PI)); // Displays: 3 trace(NumberUtilities.round(Math.PI, .01)); // Displays: 3.14 trace(NumberUtilities.round(Math.PI, .0001)); // Displays: 3.1416 trace(NumberUtilities.round(123.456, 1)); // Displays: 123 trace(NumberUtilities.round(123.456, 6)); // Displays: 126 trace(NumberUtilities.round(123.456, .01)); // Displays: 123.46 |