# Get a percentage chance out of 100% for something

I’ve already looked at most topics and they aren’t really what I want to do, I’m trying to make it so I can just figure out a percentage chance of something happening with Random.new():NextNumber() and a bit of math. Basically, a function that will just return if the percentage chance of it happening, did happen.

What i use for my crates and s**t is:

``````local random_number = math.random(0, 100)
local chanceofhappening = 2

if random_number < chanceofhappening then
--happen
end
``````

if you have more chances for multiple things that can happen you should check if the chance is between the next and the actual chance.

I use a table sorted in the order of biggest to lowest and check this way (i also have them in a folder with IntValue objects and get em from there)

``````local function sortThisTable(table_)
for i = 1, #table_ do
for x = 1, #table_ do
if x == i then
continue;
end

if table_[i].Chance.Value > table_[x].Chance.Value then
local z = table_[i]
table_[i] = table_[x]
table_[x] = z
end
end
end
end

local function getNextThingThatsGonnaHappen()
--get chances table
local itemsInCrate = {...}

sortThisShit(itemsInCrate)

local randomnumber = math.random(0, 100)

local itemsPreselected = {}

for i = 1, #itemsInCrate do
if i == #itemsInCrate then
if itemsInCrate[i].Chance.Value > randomnumber and randomnumber >= 0 then
table.insert(itemsPreselected, itemsInCrate[i])
end
elseif i == 1 then
if 100.0 >= randomnumber and randomnumber > itemsInCrate[i+1].Chance.Value then
table.insert(itemsPreselected, itemsInCrate[i])
end
elseif itemsInCrate[i].Chance.Value >= randomnumber and randomnumber > itemsInCrate[i+1].Chance.Value then
table.insert(itemsPreselected, itemsInCrate[i])
end
end
end
``````

and then i choose randomly if there’s more of the same chance in there

Hope i helped!

1 Like

Consider a similar post I replied to (obviously you will remove the Touched event and other things that are specific to the other script)

1 Like
``````local function getPercentage(successRange, totalRange)
return (successRange/totalRange) * 100
end
``````

Where `successRange` is a number value which represents a range of numbers (from 1) that would make a random event happen and where `totalRange` is a larger number value representing the whole range of numbers (from 1) of which a single number is selected at random to determine if a random event occurred.

1 Like