5.3. Rounding Numbers
Problem
You want to round a number to the nearest integer, decimal place, or interval (such as to the nearest multiple of 5).
Solution
Use Math.round( )
to round a
number to the nearest integer. Use
Math.floor( )
and Math.ceil(
)
to round a number down or up, respectively. Create a
custom roundTo( )
method to round a number to a
specified number of decimal places or to a specified multiple.
Discussion
There 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:
Decide the number of decimal places to which you want to round. For example, if you want to round 90.337 to 90.34, then you will round to two decimal places, which means that you will round to the nearest .01.
Divide the input value by the number chosen in Step 1 (in ...
Get Actionscript Cookbook now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.