Scale Range Number

You can write your topic however you want, but you need to answer these questions:

  1. What do you want to achieve? Keep it simple and clear!

made a function that scale a number with min and max

function toscale(v,inputmin,inputmax,outputmin,outputmax)

return -- scaled value


print(toscale(0,0,1,-1,1)) -- returns -1
print(toscale(0.5,0,1,-1,1)) -- returns 0
print(toscale(1,0,1,-1,1)) -- returns 1

print(toscale(0,0,1,0,255)) -- returns 0
print(toscale(0.5,0,1,0,255)) -- returns 127.5
print(toscale(1,0,1,0,255)) -- returns 255
  1. What is the issue? Include screenshots / videos if possible!

i’m try to make my self function but not works

  1. What solutions have you tried so far? Did you look for solutions on the Developer Hub?

yes but theres no similar topics

After that, you should include more details if you have any. Try to make your topic as descriptive as possible, so that it’s easier for people to help you!

-- This is an example Lua code block

Please do not ask people to write entire scripts or design entire systems for you. If you can’t answer the three questions above, you should probably pick a different category.

local function scaleNumber(number, scale, min, max)
	return math.clamp(number * scale, min, max)

i wan’t scale no limit the value

What you can do is think of these as percentages.

For example:

print(toscale(1,0,10,0,100) -- returns 10

As you can see, the input is 10% of the inputMax, and os the output is 10% of the outputMax.

The following code should do the trick if input is only between 0 and 1:

function toScale(v, outputMax)
    return v * outputMax

print(toScale(0.5, 100)) -- 50

However, if we want to supply an outputMin you need to offset it by the outputMin:

function toScale(v, outputMin, outputMax)
    local scaledOutput = outputMax - outputMin
    return v * scaledOutput + outputMin -- Add the offset
print(toScale(0.5, 10, 100)) -- 55

Now, as I stated earlier v had to be a percentage. We can get what percentage of inputMininputMax v is by a similar method:

function toScale(v, inputMin, inputMax, outputMin, outputMax)
    local scaledOutput = outputMax - outputMin
    local percentage = v / (inputMax - inputMin) -- value / max = percentage
    return percentage * scaledOutput + outputMin
print(50, 0, 100, 100, 200) -- 150
1 Like

this not work

i finded the function that i wanted

function map(s,a1,a2,b1,b2)
return b1 + (s-a1)*(b2-b1)/(a2-a1)

finally i found it!