# Rescaling A Value Between Two Ranges
**Published 11/24/2025**
If I were to pick a single piece or block of code that I would consider to be the most useful to me over all others, I would pick this one:
```csharp
internal static float ScaleToNewRangeClamped(
float oldMin, float oldMax, float newMin, float newMax, float value)
{
float OldRange = (oldMax - oldMin);
float NewRange = (newMax - newMin);
float scaledValue = (((value - oldMin) * NewRange) / OldRange) + newMin;
return Mathf.Clamp(scaledValue, newMin, newMax);
}
```
It's nothing too crazy, but I've come back to this single method — at a minimum — at least a dozen times over many different projects. What it lets you do is take a value with a known range, and map it into a new one.
For example, say you're working on a game's input logic, and you need to convert the analog input of a controller's joystick to a value that the game logic can use. It could be as simple as needing to take the joystick values, which could be a range of `0.0` to `1.0`, and convert it into a character's onscreen movement speed — let's say a range of `0` to `100`. If you have the joystick at neutral (i.e. not touching it), it reads `0`, but if the joystick is halfway tilted such that it gives a reading of `0.5`, then we need a value of `50` for moving the character as expected.
We can use this function to fix it!
```csharp
// Assume the return value of GetControllerJoystickTilt()
// is 0.5 in this case, like mentioned above
float joystickTilt = GetControllerJoystickTilt();
// We pass that value into the method along with the
// ranges that we're converting between
float characterMoveSpeed = ScaleToNewRangeClamped(
0.0f, 1.0f,
0.0f, 100f,
joystickTilt);
Debug.Log(
quot;Move speed: {characterMoveSpeed}");
// Prints: 'Move speed: 50'
```
Note the handy call into `Mathf.Clamp()` at the end, which restricts the output value to be between the given lower and upper bounds of the new range. This will guard whatever code is using said output from having to handle values that are below the expected minimum or above the expected maximum.
Thanks for reading!
— C
#blog #c_sharp #development