/**
* Returns a percentage of a value in between 2 other numbers.
* @param bottomRange low end of the range.
* @param topRange top end of the range.
* @param valueInRange value to find a range percentage of.
* @return The percentage of valueInRange in the range.
* @use getPercentWithinRange( 50, 150, 100 ); // displays 50
*/
public static function getPercentWithinRange( bottomRange:Number, topRange:Number, valueInRange:Number ):Number
{
// normalize values to work off zero
if( bottomRange < 0 )
{
var addToAll:Number = Math.abs( bottomRange );
bottomRange += addToAll;
topRange += addToAll;
valueInRange += addToAll;
}
else if( bottomRange > 0 )
{
var subFromAll:Number = Math.abs( bottomRange );
bottomRange -= subFromAll;
topRange -= subFromAll;
valueInRange -= subFromAll;
}
// simple calc to get percentage
return 100 * ( valueInRange / ( topRange - bottomRange ) );
}
A collection of handy code snippets in the languages that I use on a daily basis.
August 31, 2009
ActionScript 3: Get the percentage of a value within a number range
Sometimes, when creating UI elements or performing geometric calculations based on the sizes or positions of objects (or lots of other tasks), it's useful to find the percentage of a number within a range of 2 other numbers. Use this function to easily relate these values:
Labels:
percentage,
random number,
value
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment