Chris Paddison

Notes and Ramblings of a Software Engineer… Enjoy!

approval payday loans

Truncating and Rounding Numbers in ActionScript 3

with 3 comments

A small reference about truncating and rounding numbers in ActionScript 3.

This is a simple AS3 snippet showing how to round or truncate to a specific decimal place and how to round to the nearest multiple of a number.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
var my_number:Number = 5.2631578947368425;
 
trace("Round to whole number: "+Math.round(my_number));
trace("Round to 1 decimal place: "+Math.round(my_number*10)/10);
trace("Round to 2 decimal place: "+Math.round(my_number*100)/100);
trace("Round to 3 decimal place: "+Math.round(my_number*1000)/1000);
trace("Round to 4 decimal place: "+Math.round(my_number*10000)/10000);
trace("Round to 5 decimal place: "+Math.round(my_number*100000)/100000);
 
trace("Truncate to whole number: "+int(my_number));
trace("Truncate to 1 decimal place: "+int(my_number*10)/10);
trace("Truncate to 2 decimal place: "+int(my_number*100)/100);
trace("Truncate to 3 decimal place: "+int(my_number*1000)/1000);
trace("Truncate to 4 decimal place: "+int(my_number*10000)/10000);
trace("Truncate to 5 decimal place: "+int(my_number*100000)/100000);
 
trace("Round to nearest multiple of 5: "+Math.round(my_number/5)*5);
trace("Round to nearest multiple of 2: "+Math.round(my_number/2)*2);

…and an example snippet for rounding to a number of decimal places…

1
2
3
4
5
6
// Rounds a target number to a specific number of decimal places.
function roundToPrecision(numberVal:Number, precision:int = 0):Number
{
	var decimalPlaces:Number = Math.pow(10, precision);
	return Math.round(decimalPlaces * numberVal) / decimalPlaces;
}

…and some more rounding example ActionScript snippets…

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
// Rounds a target number "to" the nearest multiple of another number.
function roundToNearest(numberVal:Number, roundTo:Number):Number
{
	return Math.round(numberVal / roundTo) * roundTo;
}
 
// Rounds a target number "up to" the nearest multiple of another number.
function roundUpToNearest(numberVal:Number, roundTo:Number):Number
{
	return Math.ceil(numberVal / roundTo) * roundTo;
}
 
// Rounds a target number "down to" the nearest multiple of another number.
function roundDownToNearest(numberVal:Number, roundTo:Number):Number
{
	return Math.floor(numberVal / roundTo) * roundTo;
}

Written by Chris Paddison

November 17th, 2009 at 12:41 am

3 Responses to 'Truncating and Rounding Numbers in ActionScript 3'

Subscribe to comments with RSS or TrackBack to 'Truncating and Rounding Numbers in ActionScript 3'.

  1. Thank you so much!!! This post save minutes and headaches!

    Andrea

    16 Dec 11 at 12:44 pm

  2. Its a great example..all in one place! Thanks a lot.

    Komal

    5 Jan 12 at 8:15 pm

  3. Gracias, amigo!

    wrv90

    6 Jul 12 at 7:03 am

Leave a Reply