Let’s say I had a percentage chance, for example 25%, how could I make a function to return true 25% of the time and false 75% of the time?
I am currently using this:
if math.random(1, 100) <= chance then
return true
else
return false
end
This works fine, but it won’t work with percentages lower than 1, eg. 0.97%. Thanks for any help!
but then wouldn’t there be 101 integers between 0 and 1? wouldn’t this make it uneven? like a 50% chance would have a 50/101 to return false and a 51/101 to return true?
This function takes in a number between 0 and 100 (it also accepts above 100 but that will always return true), and returns either true or false.
function randomPercentage(chance)
local decimalPlaces = 6 -- every zero is another decimal place supported
return math.random(1, 100 * 10 ^ decimalPlaces) <= chance * 10 ^ decimalPlaces
end
The function supports up to 6 decimal places e.g. 0.123456. any decimals after that are just ignored. If you need more than 6 decimal places, change the value of decimalPlaces.