# How to scale / range a number

This topic is 3881 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

I was wondering, is there a way in which I can scale down a number to be within a certain range? For instance, I want a function with the following signature: float scaleRange(float number, float high, float low); an example usage is: float retVal = scaleRange(341.00f, 1.0f, -1.0f); at this point I want "retVal" to have a value between 1.0f and/or -1.0f Can someone point me in the right direction? Thanks, James

##### Share on other sites
You did specify the signature, but you didn't specify the behavior of the function you need.

For example, a function such as:
float scaleRange(float number, float high, float low){  return (high + low) * 0.5f;}
would correspond to what you asked.

##### Share on other sites
Quote:
 Original post by gp343float scaleRange(float number, float high, float low);

It depends on the range of a. If a is between 0 and 1000, you could do something like this:

return (a / 500) - 1; //scales a number from 0 to 1000 to between -1 and 1

Or, more generally:

return (a / ((aMax - aMin) / (max - min))) + min;

Where, in the previous example:

min = -1f
max = 1f
aMax = 1000f
aMin = 0f
a = 341f

float retVal = scaleRange(in, oldMin, oldMax, newMin, newMax);

eg. float retVal = scaleRange(341, 0, 1000, -1, 1);

So:

float scaleRange(float in, float oldMin, float oldMax, float newMin, float newMax)
{
return (in / ((oldMax - oldMin) / (newMax - newMin))) + newMin;
}

Of course, if you already knew some of this, such as the ranges (and they never changes) you could be more specific to speed things up.

##### Share on other sites
You can't scale an arbitrary number into a range without knowing what range that number was in beforehand.

For example:

50, is in the range 0 - 100, when scaled to the range 0.0 - 1.0 the result is 0.5.

50, is in the range 0 - 1000, when scaled to the range 0.0 - 1.0 the result is 0.05.

Specifying only the number and the scale-to range isn't enough to define a function as there are multiple possible outputs.

The way to determine the above examples is with the following formula:

n / |A| * |B| + Blower

Where:
n is the arbitrary number.
A is the scale-from range.
B is the scale-to range.

So:
Blower is the lowest value in the range B.
|A| is the size of the range A, which is equal to: Ahigher - Alower

##### Share on other sites
Hi NickHighIQ,

You function did the trick. It worked.

Many thanks,
James

1. 1
2. 2
3. 3
Rutin
21
4. 4
frob
18
5. 5

• 33
• 13
• 10
• 10
• 12
• ### Forum Statistics

• Total Topics
632568
• Total Posts
3007119

×