NumberUtil

Kind of class: public class
Package:
Inherits from:
  • none
Version: 05/19/11
Author: Aaron Clinger, David Nelson, Mike Creighton
Classpath: org.casalib.util.NumberUtil
File last modified: Friday, 20 May 2011, 00:59:45
► View source▼ Hide source
/*
    CASA Lib for ActionScript 3.0
    Copyright (c) 2011, Aaron Clinger & Contributors of CASA Lib
    All rights reserved.
    
    Redistribution and use in source and binary forms, with or without
    modification, are permitted provided that the following conditions are met:
    
    - Redistributions of source code must retain the above copyright notice,
      this list of conditions and the following disclaimer.
    
    - Redistributions in binary form must reproduce the above copyright notice,
      this list of conditions and the following disclaimer in the documentation
      and/or other materials provided with the distribution.
    
    - Neither the name of the CASA Lib nor the names of its contributors
      may be used to endorse or promote products derived from this software
      without specific prior written permission.
    
    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
    AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
    IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
    ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
    LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
    CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
    SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
    INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
    CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
    ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
    POSSIBILITY OF SUCH DAMAGE.
*/
package org.casalib.util {
    import org.casalib.math.Percent;
    
    
    /**
        Provides utility functions for manipulating numbers.
        
        @author Aaron Clinger
        @author David Nelson
        @author Mike Creighton
        @version 05/19/11
    */
    public class NumberUtil {
        
        /**
            Determines if the two values are equal, with the option to define the precision.
            
            @param val1: A value to compare.
            @param val2: A value to compare.
            @param precision: The maximum amount the two values can differ and still be considered equal.
            @return Returns true the values are equal; otherwise false.
            @example
                
                    trace(NumberUtil.isEqual(3.042, 3, 0)); // Traces false
                    trace(NumberUtil.isEqual(3.042, 3, 0.5)); // Traces true
                
        */
        public static function isEqual(val1:Number, val2:Number, precision:Number = 0):Boolean {
            return Math.abs(val1 - val2) <= Math.abs(precision);
        }
        
        /**
            Evaluates val1 and val2 and returns the smaller value. Unlike Math.min this method will return the defined value if the other value is null or not a number.
            
            @param val1: A value to compare.
            @param val2: A value to compare.
            @return Returns the smallest value, or the value out of the two that is defined and valid.
            @example
                
                    trace(NumberUtil.min(5, null)); // Traces 5
                    trace(NumberUtil.min(5, "CASA")); // Traces 5
                    trace(NumberUtil.min(5, 13)); // Traces 5
                
        */
        public static function min(val1:*, val2:*):Number {
            if (isNaN(val1) && isNaN(val2) || val1 == null && val2 == null)
                return NaN;
            
            if (val1 == null || val2 == null)
                return (val2 == null) ? val1 : val2;
            
            if (isNaN(val1) || isNaN(val2))
                return isNaN(val2) ? val1 : val2;
            
            return Math.min(val1, val2);
        }
        
        /**
            Evaluates val1 and val2 and returns the larger value. Unlike Math.max this method will return the defined value if the other value is null or not a number.
            
            @param val1: A value to compare.
            @param val2: A value to compare.
            @return Returns the largest value, or the value out of the two that is defined and valid.
            @example
                
                    trace(NumberUtil.max(-5, null)); // Traces -5
                    trace(NumberUtil.max(-5, "CASA")); // Traces -5
                    trace(NumberUtil.max(-5, -13)); // Traces -5
                
        */
        public static function max(val1:*, val2:*):Number {
            if (isNaN(val1) && isNaN(val2) || val1 == null && val2 == null)
                return NaN;
            
            if (val1 == null || val2 == null)
                return (val2 == null) ? val1 : val2;
            
            if (isNaN(val1) || isNaN(val2))
                return (isNaN(val2)) ? val1 : val2;
            
            return Math.max(val1, val2);
        }
        
        /**
            Creates a random number within the defined range.
            
            @param min: The minimum value the random number can be.
            @param min: The maximum value the random number can be.
            @return Returns a random number within the range.
        */
        public static function randomWithinRange(min:Number, max:Number):Number {
            return min + (Math.random() * (max - min));
        }
        
        /**
            Creates a random integer within the defined range.
            
            @param min: The minimum value the random integer can be.
            @param min: The maximum value the random integer can be.
            @return Returns a random integer within the range.
        */
        public static function randomIntegerWithinRange(min:int, max:int):int {
            return Math.floor(Math.random() * (1 + max - min) + min);
        }
        
        /**
            Determines if the number is even.
            
            @param value: A number to determine if it is divisible by 2.
            @return Returns true if the number is even; otherwise false.
            @example
                
                    trace(NumberUtil.isEven(7)); // Traces false
                    trace(NumberUtil.isEven(12)); // Traces true
                
        */
        public static function isEven(value:Number):Boolean {
            return (value & 1) == 0;
        }
        
        /**
            Determines if the number is odd.
            
            @param value: A number to determine if it is not divisible by 2.
            @return Returns true if the number is odd; otherwise false.
            @example
                
                    trace(NumberUtil.isOdd(7)); // Traces true
                    trace(NumberUtil.isOdd(12)); // Traces false
                
        */
        public static function isOdd(value:Number):Boolean {
            return !NumberUtil.isEven(value);
        }
        
        /**
            Determines if the number is an integer.
            
            @param value: A number to determine if it contains no decimal values.
            @return Returns true if the number is an integer; otherwise false.
            @example
                
                    trace(NumberUtil.isInteger(13)); // Traces true
                    trace(NumberUtil.isInteger(1.2345)); // Traces false
                
        */
        public static function isInteger(value:Number):Boolean {
            return (value % 1) == 0;
        }
        
        /**
            Determines if the number is prime.
            
            @param value: A number to determine if it is only divisible by 1 and itself.
            @return Returns true if the number is prime; otherwise false.
            @example
                
                    trace(NumberUtil.isPrime(13)); // Traces true
                    trace(NumberUtil.isPrime(4)); // Traces false
                
        */
        public static function isPrime(value:Number):Boolean {
            if (value == 1 || value == 2)
                return true;
            
            if (NumberUtil.isEven(value))
                return false;
            
            var s:Number = Math.sqrt(value);
            for (var i:Number = 3; i <= s; i++)
                if (value % i == 0)
                    return false;
            
            return true;
        }
        
        /**
            Rounds a number's decimal value to a specific place.
            
            @param value: The number to round.
            @param place: The decimal place to round.
            @return Returns the value rounded to the defined place. 
            @example
                
                    trace(NumberUtil.roundToPlace(3.14159, 2)); // Traces 3.14
                    trace(NumberUtil.roundToPlace(3.14159, 3)); // Traces 3.142
                
        */
        public static function roundDecimalToPlace(value:Number, place:uint):Number {
            var p:Number = Math.pow(10, place);
            
            return Math.round(value * p) / p;
        }
        
        /**
            Determines if index is included within the collection length otherwise the index loops to the beginning or end of the range and continues.
            
            @param index: Index to loop if needed.
            @param length: The total elements in the collection.
            @return A valid zero-based index.
            @example
                
                    var colors:Array = new Array("Red", "Green", "Blue");
                    
                    trace(colors[NumberUtil.loopIndex(2, colors.length)]); // Traces Blue
                    trace(colors[NumberUtil.loopIndex(4, colors.length)]); // Traces Green
                    trace(colors[NumberUtil.loopIndex(-6, colors.length)]); // Traces Red
                
        */
        public static function loopIndex(index:int, length:uint):uint {
            if (index < 0)
                index = length + index % length;
            
            if (index >= length)
                return index % length;
            
            return index;
        }
        
        /**
            Determines if the value is included within a range.
            
            @param value: Number to determine if it is included in the range.
            @param firstValue: First value of the range.
            @param secondValue: Second value of the range.
            @return Returns true if the number falls within the range; otherwise false.
            @usageNote The range values do not need to be in order.
            @example
                
                    trace(NumberUtil.isBetween(3, 0, 5)); // Traces true
                    trace(NumberUtil.isBetween(7, 0, 5)); // Traces false
                
        */
        public static function isBetween(value:Number, firstValue:Number, secondValue:Number):Boolean {
            return !(value < Math.min(firstValue, secondValue) || value > Math.max(firstValue, secondValue));
        }
        
        /**
            Determines if value falls within a range; if not it is snapped to the nearest range value.
            
            @param value: Number to determine if it is included in the range.
            @param firstValue: First value of the range.
            @param secondValue: Second value of the range.
            @return Returns either the number as passed, or its value once snapped to nearest range value.
            @usageNote The constraint values do not need to be in order.
            @example
                
                    trace(NumberUtil.constrain(3, 0, 5)); // Traces 3
                    trace(NumberUtil.constrain(7, 0, 5)); // Traces 5
                
        */
        public static function constrain(value:Number, firstValue:Number, secondValue:Number):Number {
            return Math.min(Math.max(value, Math.min(firstValue, secondValue)), Math.max(firstValue, secondValue));
        }
        
        /**
            Creates evenly spaced numerical increments between two numbers.
            
            @param begin: The starting value.
            @param end: The ending value.
            @param steps: The number of increments between the starting and ending values.
            @return Returns an Array comprised of the increments between the two values.
            @example
                
                    trace(NumberUtil.createStepsBetween(0, 5, 4)); // Traces 1,2,3,4
                    trace(NumberUtil.createStepsBetween(1, 3, 3)); // Traces 1.5,2,2.5
                
        */
        public static function createStepsBetween(begin:Number, end:Number, steps:Number):Array {
            steps++;
            
            var i:uint = 0;
            var stepsBetween:Array = new Array();
            var increment:Number = (end - begin) / steps;
            
            while (++i < steps)
                stepsBetween.push((i * increment) + begin);
            
            return stepsBetween;
        }
        
        /**
            Determines a value between two specified values.
            
            @param amount: The level of interpolation between the two values. If 0%, begin value is returned; if 100%, end value is returned.
            @param begin: The starting value.
            @param end: The ending value.
            @example
                
                    trace(NumberUtil.interpolate(new Percent(0.5), 0, 10)); // Traces 5
                
        */
        public static function interpolate(amount:Percent, begin:Number, end:Number):Number {
            return begin + (end - begin) * amount.decimalPercentage;
        }
        
        /**
            Determines a percentage of a value in a given range.
            
            @param value: The value to be converted.
            @param minimum: The lower value of the range.
            @param maximum: The upper value of the range.
            @example
                
                    trace(NumberUtil.normalize(8, 4, 20).decimalPercentage); // Traces 0.25
                
        */
        public static function normalize(value:Number, minimum:Number, maximum:Number):Percent {
            return new Percent((value - minimum) / (maximum - minimum));
        }
        
        /**
            Maps a value from one coordinate space to another.
            
            @param value: Value from the input coordinate space to map to the output coordinate space.
            @param min1: Starting value of the input coordinate space.
            @param max1: Ending value of the input coordinate space.
            @param min2: Starting value of the output coordinate space.
            @param max2: Ending value of the output coordinate space.
            @example
                
                    trace(NumberUtil.map(0.75, 0, 1, 0, 100)); // Traces 75
                
        */
        public static function map(value:Number, min1:Number, max1:Number, min2:Number, max2:Number):Number {
            return min2 + (max2 - min2) * ((value - min1) / (max1 - min1));
        }
        
        /**
            Low pass filter alogrithm for easing a value toward a destination value. Works best for tweening values when no definite time duration exists and when the destination value changes.
            
            If (0.5 < n < 1), then the resulting values will overshoot (ping-pong) until they reach the destination value. When n is greater than 1, as its value increases, the time it takes to reach the destination also increases. A pleasing value for n is 5.
            
            @param value: The current value.
            @param dest: The destination value.
            @param n: The slowdown factor.
            @return The weighted average.
        */
        public static function getWeightedAverage(value:Number, dest:Number, n:Number):Number {
            return value + (dest - value) / n;
        }
        
        /**
            Formats a number as a string.
            
            @param value: The number you wish to format.
            @param kDelim: The character used to seperate thousands; defaults to "".
            @param minLength: The minimum length of the number; defaults to 0 .
            @param fillChar: The leading character used to make the number the minimum length; defaults to "0".
            @return Returns the formatted number as a String.
            @example
                
                    trace(NumberUtil.format(1234567, ",", 8)); // Traces 01,234,567
                
        */
        public static function format(value:Number, kDelim:String = ",", minLength:uint = 0, fillChar:String = "0"):String {
            const remainder:Number = value % 1;
            var num:String         = Math.floor(value).toString();
            const len:uint         = num.length;
            
            if (minLength != 0 && minLength > len) {
                minLength -= len;
                
                const addChar:String = fillChar || '0';
                
                while (minLength--)
                    num = addChar + num;
            }
            
            if (kDelim != null && num.length > 3) {
                const totalDelim:uint  = Math.floor(num.length / 3);
                const totalRemain:uint = num.length % 3;
                const numSplit:Array   = num.split('');
                var i:int              = -1;
                
                while (++i < totalDelim)
                    numSplit.splice(totalRemain + (4 * i), 0, kDelim);
                
                if (totalRemain == 0)
                    numSplit.shift();
                
                num = numSplit.join('');
            }
            
            if (remainder != 0)
                num += remainder.toString().substr(1);
            
            return num;
        }
        
        /**
            Formats a number as a currency string.
            
            @param value: The number you wish to format.
            @param forceDecimals: If the number should always have two decimal places true, or only show decimals is there is a decimals value false; defaults to true.
            @param kDelim: The character used to seperate thousands; defaults to ",".
            @return Returns the formatted number as a String.
            @example
                
                    trace(NumberUtil.formatCurrency(1234.5)); // Traces "1,234.50"
                
        */
        public static function formatCurrency(value:Number, forceDecimals:Boolean = true, kDelim:String = ","):String {
            const remainder:Number = value % 1;
            var currency:String    = NumberUtil.format(Math.floor(value), kDelim);
            
            if (remainder != 0 || forceDecimals)
                currency += remainder.toFixed(2).substr(1);
            
            return currency;
        } 
        
        /**
            Finds the english ordinal suffix for the number given.
            
            @param value: Number to find the ordinal suffix of.
            @return Returns the suffix for the number, 2 characters.
            @example
                
                    trace(32 + NumberUtil.getOrdinalSuffix(32)); // Traces 32nd
                
        */
        public static function getOrdinalSuffix(value:int):String {
            if (value >= 10 && value <= 20)
                return 'th';
            
            if (value == 0)
                return '';
            
            switch (value % 10) {
                case 3 :
                    return 'rd';
                case 2 :
                    return 'nd';
                case 1 :
                    return 'st';
                default :
                    return 'th';
            }
        }
        
        /**
            Adds a leading zero for numbers less than ten.
            
            @param value: Number to add leading zero.
            @return Number as a String; if the number was less than ten the number will have a leading zero.
            @example
                
                    trace(NumberUtil.addLeadingZero(7)); // Traces 07
                    trace(NumberUtil.addLeadingZero(11)); // Traces 11
                
        */
        public static function addLeadingZero(value:Number):String {
            return (value < 10) ? '0' + value : value.toString();
        }
        
        /**
            Spells the provided number.
            
            @param value: Number to spell. Needs to be less than 999999999.
            @return The number spelled out as a String.
            @throws Error if value is greater than 999999999.
            @example
                
                    trace(NumberUtil.spell(0)); // Traces Zero
                    trace(NumberUtil.spell(23)); // Traces Twenty-Three
                    trace(NumberUtil.spell(2005678)); // Traces Two Million, Five Thousand, Six Hundred Seventy-Eight
                
        */
        public static function spell(value:uint):String {
            if (value > 999999999)
                throw new Error('Value too large for this method.');
            
            const onesSpellings:Array = new Array('', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Eleven', 'Twelve', 'Thirteen', 'Fourteen', 'Fifteen', 'Sixteen', 'Seventeen', 'Eighteen', 'Nineteen');
            const tensSpellings:Array = new Array('', '', 'Twenty', 'Thirty', 'Forty', 'Fifty', 'Sixty', 'Seventy', 'Eighty', 'Ninety');
            var spelling:String       = '';
            
            const millions:uint = value / 1000000;
            value              %= 1000000;
            
            const thousands:uint = value / 1000;
            value               %= 1000;
            
            const hundreds:uint = value / 100;
            value              %= 100;
            
            const tens:uint = value / 10;
            value          %= 10;
            
            const ones:uint = value % 10;
            
            if (millions != 0) {
                spelling += (spelling.length == 0) ? '' : ', ';
                spelling += NumberUtil.spell(millions) + ' Million';
            }
            
            if (thousands != 0) {
                spelling += (spelling.length == 0) ? '' : ', ';
                spelling += NumberUtil.spell(thousands) + ' Thousand';
            }
            
            if (hundreds != 0) {
                spelling += (spelling.length == 0) ? '' : ', ';
                spelling += NumberUtil.spell(hundreds) + ' Hundred';
            }
            
            if (tens != 0 || ones != 0) {
                spelling += (spelling.length == 0) ? '' : ' ';
                
                if (tens < 2)
                    spelling += onesSpellings[tens * 10 + ones];
                else {
                    spelling += tensSpellings[tens];
                    
                    if (ones != 0)
                        spelling += '-' + onesSpellings[ones];
                }
            }
            
            if (spelling.length == 0)
                return 'Zero';
            
            return spelling;
        }
    }
}
Provides utility functions for manipulating numbers.

Summary

Class methods
  • isEqual (val1:Number, val2:Number, precision:Number) : Boolean
    • Determines if the two values are equal, with the option to define the precision.
  • min (val1 = *, val2 = *) : Number
    • Evaluates val1 and val2 and returns the smaller value.
  • max (val1 = *, val2 = *) : Number
    • Evaluates val1 and val2 and returns the larger value.
  • randomWithinRange (min:Number, max:Number) : Number
    • Creates a random number within the defined range.
  • randomIntegerWithinRange (min:int, max:int) : int
    • Creates a random integer within the defined range.
  • isEven (value:Number) : Boolean
    • Determines if the number is even.
  • isOdd (value:Number) : Boolean
    • Determines if the number is odd.
  • isInteger (value:Number) : Boolean
    • Determines if the number is an integer.
  • isPrime (value:Number) : Boolean
    • Determines if the number is prime.
  • roundDecimalToPlace (value:Number, place:uint) : Number
    • Rounds a number's decimal value to a specific place.
  • loopIndex (index:int, length:uint) : uint
    • Determines if index is included within the collection length otherwise the index loops to the beginning or end of the range and continues.
  • isBetween (value:Number, firstValue:Number, secondValue:Number) : Boolean
    • Determines if the value is included within a range.
  • constrain (value:Number, firstValue:Number, secondValue:Number) : Number
    • Determines if value falls within a range; if not it is snapped to the nearest range value.
  • createStepsBetween (begin:Number, end:Number, steps:Number) : Array
    • Creates evenly spaced numerical increments between two numbers.
  • interpolate (amount:Percent, begin:Number, end:Number) : Number
    • Determines a value between two specified values.
  • normalize (value:Number, minimum:Number, maximum:Number) : Percent
    • Determines a percentage of a value in a given range.
  • map (value:Number, min1:Number, max1:Number, min2:Number, max2:Number) : Number
    • Maps a value from one coordinate space to another.
  • getWeightedAverage (value:Number, dest:Number, n:Number) : Number
    • Low pass filter alogrithm for easing a value toward a destination value.
  • format (value:Number, kDelim:String = ",", minLength:uint, fillChar:String = "0") : String
    • Formats a number as a string.
  • formatCurrency (value:Number, forceDecimals:Boolean = true, kDelim:String = ",") : String
    • Formats a number as a currency string.
  • getOrdinalSuffix (value:int) : String
    • Finds the english ordinal suffix for the number given.
  • addLeadingZero (value:Number) : String
    • Adds a leading zero for numbers less than ten.
  • spell (value:uint) : String
    • Spells the provided number.

Class methods

addLeadingZero

static function addLeadingZero(value:Number) : String

Adds a leading zero for numbers less than ten.

Parameters
value:Number to add leading zero.
Example
  • trace(NumberUtil.addLeadingZero(7)); // Traces 07
    trace(NumberUtil.addLeadingZero(11)); // Traces 11
    
Returns
  • Number as a String; if the number was less than ten the number will have a leading zero.

constrain

static function constrain(value:Number, firstValue:Number, secondValue:Number) : Number

Determines if value falls within a range; if not it is snapped to the nearest range value.

Parameters
value :Number to determine if it is included in the range.
firstValue :First value of the range.
secondValue:Second value of the range.
Example
  • trace(NumberUtil.constrain(3, 0, 5)); // Traces 3
    trace(NumberUtil.constrain(7, 0, 5)); // Traces 5
    
Returns
  • Returns either the number as passed, or its value once snapped to nearest range value.
Usage note
  • The constraint values do not need to be in order.

createStepsBetween

static function createStepsBetween(begin:Number, end:Number, steps:Number) : Array

Creates evenly spaced numerical increments between two numbers.

Parameters
begin:The starting value.
end :The ending value.
steps:The number of increments between the starting and ending values.
Example
  • trace(NumberUtil.createStepsBetween(0, 5, 4)); // Traces 1,2,3,4
    trace(NumberUtil.createStepsBetween(1, 3, 3)); // Traces 1.5,2,2.5
    
Returns
  • Returns an Array comprised of the increments between the two values.

format

static function format(value:Number, kDelim:String = ",", minLength:uint, fillChar:String = "0") : String

Formats a number as a string.

Parameters
value :The number you wish to format.
kDelim :The character used to seperate thousands; defaults to "".
minLength:The minimum length of the number; defaults to 0.
fillChar :The leading character used to make the number the minimum length; defaults to "0".
Example
  • trace(NumberUtil.format(1234567, ",", 8)); // Traces 01,234,567
Returns
  • Returns the formatted number as a String.

formatCurrency

static function formatCurrency(value:Number, forceDecimals:Boolean = true, kDelim:String = ",") : String

Formats a number as a currency string.

Parameters
value :The number you wish to format.
forceDecimals:If the number should always have two decimal places true, or only show decimals is there is a decimals value false; defaults to true.
kDelim :The character used to seperate thousands; defaults to ",".
Example
  • trace(NumberUtil.formatCurrency(1234.5)); // Traces "1,234.50"
Returns
  • Returns the formatted number as a String.

getOrdinalSuffix

static function getOrdinalSuffix(value:int) : String

Finds the english ordinal suffix for the number given.

Parameters
value:Number to find the ordinal suffix of.
Example
  • trace(32 + NumberUtil.getOrdinalSuffix(32)); // Traces 32nd
Returns
  • Returns the suffix for the number, 2 characters.

getWeightedAverage

static function getWeightedAverage(value:Number, dest:Number, n:Number) : Number

Low pass filter alogrithm for easing a value toward a destination value. Works best for tweening values when no definite time duration exists and when the destination value changes. If (0.5 < n < 1), then the resulting values will overshoot (ping-pong) until they reach the destination value. When n is greater than 1, as its value increases, the time it takes to reach the destination also increases. A pleasing value for n is 5.

Parameters
value:The current value.
dest :The destination value.
n :The slowdown factor.
Returns
  • The weighted average.

interpolate

static function interpolate(amount:Percent, begin:Number, end:Number) : Number

Determines a value between two specified values.

Parameters
amount:The level of interpolation between the two values. If 0%, begin value is returned; if 100%, end value is returned.
begin :The starting value.
end :The ending value.
Example
  • trace(NumberUtil.interpolate(new Percent(0.5), 0, 10)); // Traces 5

isBetween

static function isBetween(value:Number, firstValue:Number, secondValue:Number) : Boolean

Determines if the value is included within a range.

Parameters
value :Number to determine if it is included in the range.
firstValue :First value of the range.
secondValue:Second value of the range.
Example
  • trace(NumberUtil.isBetween(3, 0, 5)); // Traces true
    trace(NumberUtil.isBetween(7, 0, 5)); // Traces false
    
Returns
  • Returns true if the number falls within the range; otherwise false.
Usage note
  • The range values do not need to be in order.

isEqual

static function isEqual(val1:Number, val2:Number, precision:Number) : Boolean

Determines if the two values are equal, with the option to define the precision.

Parameters
val1 :A value to compare.
val2 :A value to compare.
precision:The maximum amount the two values can differ and still be considered equal.
Example
  • trace(NumberUtil.isEqual(3.042, 3, 0)); // Traces false
    trace(NumberUtil.isEqual(3.042, 3, 0.5)); // Traces true
    
Returns
  • Returns true the values are equal; otherwise false.

isEven

static function isEven(value:Number) : Boolean

Determines if the number is even.

Parameters
value:A number to determine if it is divisible by 2.
Example
  • trace(NumberUtil.isEven(7)); // Traces false
    trace(NumberUtil.isEven(12)); // Traces true
    
Returns
  • Returns true if the number is even; otherwise false.

isInteger

static function isInteger(value:Number) : Boolean

Determines if the number is an integer.

Parameters
value:A number to determine if it contains no decimal values.
Example
  • trace(NumberUtil.isInteger(13)); // Traces true
    trace(NumberUtil.isInteger(1.2345)); // Traces false
    
Returns
  • Returns true if the number is an integer; otherwise false.

isOdd

static function isOdd(value:Number) : Boolean

Determines if the number is odd.

Parameters
value:A number to determine if it is not divisible by 2.
Example
  • trace(NumberUtil.isOdd(7)); // Traces true
    trace(NumberUtil.isOdd(12)); // Traces false
    
Returns
  • Returns true if the number is odd; otherwise false.

isPrime

static function isPrime(value:Number) : Boolean

Determines if the number is prime.

Parameters
value:A number to determine if it is only divisible by 1 and itself.
Example
  • trace(NumberUtil.isPrime(13)); // Traces true
    trace(NumberUtil.isPrime(4)); // Traces false
    
Returns
  • Returns true if the number is prime; otherwise false.

loopIndex

static function loopIndex(index:int, length:uint) : uint

Determines if index is included within the collection length otherwise the index loops to the beginning or end of the range and continues.

Parameters
index :Index to loop if needed.
length:The total elements in the collection.
Example
  • var colors:Array = new Array("Red", "Green", "Blue");
    
    trace(colors[NumberUtil.loopIndex(2, colors.length)]); // Traces Blue
    trace(colors[NumberUtil.loopIndex(4, colors.length)]); // Traces Green
    trace(colors[NumberUtil.loopIndex(-6, colors.length)]); // Traces Red
    
Returns
  • A valid zero-based index.

map

static function map(value:Number, min1:Number, max1:Number, min2:Number, max2:Number) : Number

Maps a value from one coordinate space to another.

Parameters
value:Value from the input coordinate space to map to the output coordinate space.
min1 :Starting value of the input coordinate space.
max1 :Ending value of the input coordinate space.
min2 :Starting value of the output coordinate space.
max2 :Ending value of the output coordinate space.
Example
  • trace(NumberUtil.map(0.75, 0, 1, 0, 100)); // Traces 75

max

static function max(val1 = *, val2 = *) : Number

Evaluates val1 and val2 and returns the larger value. Unlike Math.max this method will return the defined value if the other value is null or not a number.

Parameters
val1:A value to compare.
val2:A value to compare.
Example
  • trace(NumberUtil.max(-5, null)); // Traces -5
    trace(NumberUtil.max(-5, "CASA")); // Traces -5
    trace(NumberUtil.max(-5, -13)); // Traces -5
    
Returns
  • Returns the largest value, or the value out of the two that is defined and valid.

min

static function min(val1 = *, val2 = *) : Number

Evaluates val1 and val2 and returns the smaller value. Unlike Math.min this method will return the defined value if the other value is null or not a number.

Parameters
val1:A value to compare.
val2:A value to compare.
Example
  • trace(NumberUtil.min(5, null)); // Traces 5
    trace(NumberUtil.min(5, "CASA")); // Traces 5
    trace(NumberUtil.min(5, 13)); // Traces 5
    
Returns
  • Returns the smallest value, or the value out of the two that is defined and valid.

normalize

static function normalize(value:Number, minimum:Number, maximum:Number) : Percent

Determines a percentage of a value in a given range.

Parameters
value :The value to be converted.
minimum:The lower value of the range.
maximum:The upper value of the range.
Example
  • trace(NumberUtil.normalize(8, 4, 20).decimalPercentage); // Traces 0.25

randomIntegerWithinRange

static function randomIntegerWithinRange(min:int, max:int) : int

Creates a random integer within the defined range.

Parameters
min:The minimum value the random integer can be.
min:The maximum value the random integer can be.
Returns
  • Returns a random integer within the range.

randomWithinRange

static function randomWithinRange(min:Number, max:Number) : Number

Creates a random number within the defined range.

Parameters
min:The minimum value the random number can be.
min:The maximum value the random number can be.
Returns
  • Returns a random number within the range.

roundDecimalToPlace

static function roundDecimalToPlace(value:Number, place:uint) : Number

Rounds a number's decimal value to a specific place.

Parameters
value:The number to round.
place:The decimal place to round.
Example
  • trace(NumberUtil.roundToPlace(3.14159, 2)); // Traces 3.14
    trace(NumberUtil.roundToPlace(3.14159, 3)); // Traces 3.142
    
Returns
  • Returns the value rounded to the defined place.

spell

static function spell(value:uint) : String

Spells the provided number.

Parameters
value:Number to spell. Needs to be less than 999999999.
Example
  • trace(NumberUtil.spell(0)); // Traces Zero
    trace(NumberUtil.spell(23)); // Traces Twenty-Three
    trace(NumberUtil.spell(2005678)); // Traces Two Million, Five Thousand, Six Hundred Seventy-Eight
    
Returns
  • The number spelled out as a String.
Throws
  • Error if value is greater than 999999999.