Code Tip: Percentage to Value – Value to Percentage

While on a project just recently, I was in need of calculating a percentage of a certain value which is in a specified range and then to convert back this percentage to equivalent value of another range.

For example, if I have a range of integers from 0 to 50 and I need to find an equivalent percentage of the value of 25 within this range, the resulting percentage would be 50%. And now if I take this 50% and find an equivalent value within another range of 50 to 100, the resulting value would be 75.

Tried to find a utility class for this type of basic percentage-to-value conversion over the internet but couldn’t find so I wrote my own. Here it is:

package com.tahirahmed.utils
{

/**
* Number Utilities
*
* …
* @author Tahir Ahmed – lukin4ward@hotmail.com
* @version 1.0
*/
public class NumUtils
{

public function NumUtils ( )
{
}

/**
* Determines an equivalent percentage of a value within a given range
*
*
* @param value the value to which the equivalent percentage needs to be calculated
* @param min the lower value of the range
* @param max the upper value of the range
* @return percentage the resulting percentage of the given value within the specified range
* @example
*
* NumUtils.getPercentage ( 5, 0, 10 ); // returns 50
*

*/
public static function getPercentage ( value:Number, min:Number, max:Number ):Number
{
var percentage :Number = ((( value – min ) / ( max – min )) * 100 );

return percentage;
}

/**
* Determines an equivalent value of a percentage within a given range
*
*
* @param percentage the percentage to which the equivalent value needs to be calculated
* @param min the lower value of the range
* @param max the upper value of the range
* @return value the resulting value of the given percentage within the specified range
* @example
*
* NumUtils.getValue ( 50, 0, 10 ); // returns 5
*

*/
public static function getValue ( percentage:Number, min:Number, max:Number ):Number
{
var value :Number = ((( max – min ) / 100 ) * percentage ) + min;

return value;
}
}
}

Download it from here.

Advertisements
Code Tip: Percentage to Value – Value to Percentage

One thought on “Code Tip: Percentage to Value – Value to Percentage

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s