# How would I get a number between 0-1 with a min and max value?

What I’m trying to do is getting a number between 0-1 dependent on a low and high value.
If the value is below or at the low, the number is one.
If the value is above or at the high, the number is zero.
The problem is the numbers in between the low and high, how would I go about getting the decimal number?

Here’s how it would look:

``````local low = 10
local high = 20

local function getValue(value:number)
if value >= high then
return 0
elseif value <= low then
return 1
else
-- I don't know what to do here
end
end

getValue(20) -- 0
getValue(30) -- 0

getValue(10) -- 1
getValue(5) -- 1

getValue(15) -- would be 0.5, but I don't know how to get to this value
``````

Sorry if there is a easily known formula for this or if I’m not being concise, I don’t really know how to explain this or what to call it. Any help or questions on how I can explain this better would be appreciated!

2 Likes

Subtract low from the given number and divide the result with high-low

``````local low = 10
local high = 20

local function getValue(value:number)
if value >= high then
return 0
elseif value <= low then
return 1
else
return (value-low)/(high-low)
end
end
``````
2 Likes

You can get the percentage from low to high, then clamp it to 0 and 1:

``````local low = 10
local high = 20

local function getValue(x: number): number
local range = high - low
return math.clamp(1 - (x - low) / range, 0, 1)
end

print(getValue(10)) --> 1
print(getValue(20)) --> 0
print(getValue(15)) --> 0.5
``````
4 Likes

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.