q1vhrq
Last Updated: February 25, 2016
·
300
· depl0y

Calculating the percentage from a point within a range

Thanks to an awesome answer on math.stackexchange.com I just wanted to make a note to self. For quite a few controls it is needed to calculate the percentage of a certain point within a range (for example when building a custom slider control).

Let's say we have the following values:

float _minValue = 0;
float _maxValue = 200;
float _value = 50;

Using simple values here, to demonstrate that it works.

float _percentage = ((_value - _minValue) / (_maxValue - _minValue)) * 100;

This ends up in:

((50 - 0) / (200 - 0)) * 100 = 25

But we already knew that 50 is 25% in a 0 to 200 scale, right? But now lets do it the other way around. Let's say we have the following values:

float _minValue = 0;
float _maxValue = 200;
float _percentage = 25;

Now we can calculate the value that belongs with that percentage on the specified scale:

float _value = (1.0f/100.0f) * ((_percentage * _maxValue) + (100 * _minValue) - (_percentage * _minValue));

This ends up in:

(1/100) * ((25 * 200) + (100 * 0) - (25 * 0)) = 50

Amazing, right? This also works with ranges that have negative _minValue's, etc.