MathUtils

Class to extend the functionality of the Math class. I have used this class many times in projects. I mostly use
MathUtils.randomBetween, but I have also found many uses for the other
functions. Hope they help you too.

roundPrecision(number:Number, precision:int = 0):Number
Rounds a number to a specified number of decimal places

randomBetween(min:Number = 0, max:Number = 99999999, precision:int = 0):Number
Generates a random number and rounds to a specified number of decimal places

randomBetweenRound(min:Number = 0, max:Number = 99999999):Number
Generates a random number and rounds to the nearest whole number

randomBetweenFloor(min:Number = 0, max:Number = 99999999):Number
Generates a random number and rounds down to the nearest whole number

randomBetweenCeil(min:Number = 0, max:Number = 99999999):Number
Generates a random number and rounds up to the nearest whole number

Class version:
1.0
Last Updated:
July 3, 2009
Requires:
Actionscript 3
Download:
http://freerksen.googlecode.com/files/flex_mathutils.zip

Source:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package com.witheringtree.utils
{
	/**
	 * Utility functions to extend the Math class.
	 */
	public class MathUtils
	{
		/**
		 * Rounds a number to a specific number of decimal places.
		 */
		public static function roundPrecision(number:Number, precision:int=0):Number
		{
			var places:Number = Math.pow(10, precision);
			return Math.round(places * number) / places;
		}
		/**
		 * Generates a random number between two number values.
		 */
		public static function randomBetween(min:Number=0, max:Number=99999999, precision:int=0):Number
		{
			return roundPrecision(Math.random() * (max - min) + min, precision);
		}
		/**
		 * Generates a random number between two number values and round to the nearest whole number.
		 */
		public static function randomBetweenRound(min:Number=0, max:Number=99999999):Number
		{
			return Math.round(randomBetween(min, max));
		}
		/**
		 * Generates a random number between two number values and rounds down to the nearest whole number.
		 */
		public static function randomBetweenFloor(min:Number=0, max:Number=99999999):Number
		{
			return Math.floor(randomBetween(min, max));
		}
		/**
		 * Generates a random number between two number values and rounds up to the nearest whole number.
		 */
		public static function randomBetweenCeil(min:Number=0, max:Number=99999999):Number
		{
			return Math.ceil(randomBetween(min, max));
		}
	}
}

Usage:

1
2
3
4
5
MathUtils.roundPrecision(123.456);
MathUtils.randomBetween(5, 10);
MathUtils.randomBetweenRound(5, 10);
MathUtils.randomBetweenFloor(5, 10);
MathUtils.randomBetweenCeil(5, 10);

There are no comments

Add a Comment

Allowed tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">