Reducing a value with math.random

  1. What do you want to achieve? Hello, so i want to reduce a value with math.random but it don’t work, that’s how i do it : game.Workspace.ValueToChange.Value = game.Workspace.ValueToChange.Value - math.random(0.1, 0.2)

(I use a numbervalue)

  1. What is the issue? The value don’t change.

  2. What solutions have you tried so far? I looked on forums.

math.random will only work for whole numbers, so to generate a number between 0.1 and 0.2 you have to do math.random(1,2)/10

2 Likes

Okay, it worked but i encounter another issue on my textlabels that display the value at the end of the number it’s like that : 25.2 but there is a lot of 0 at the end of the number like that : 25.200000000000000

This is related to an update Roblox made recently, which is related to the way computers store floats. When you’re assigning to the TextLabel, try this:

local function decimalRound(num, places)
  local power = 10^places
  return math.round(num * power) / power
end
textlabelpath.Text = tostring(decimalRound(game.Workspace.ValueToChange.Value, 4))

For anyone looking for the answer of the original question:

@Neplioz Kinda late, but consider marking that answer as the solution because I fixed an unrelated (and small) problem not stated in the title whereas he fixed the problem in the title.

Try doing this:

local randomNumber = math.random(.1,.2)


workspace.ValueToChange.Value += randomNumber

math.random returns a Integer, which cannot use decimals

Use the whole number and if you want 0.1 to 0.2 use

math.random(1,2)/10

This should give you the result

and for the massive decimal issue

math.floor(value * 10) / 10

Try using this to get just 1 decimal

Not always, mat.random() (no arguments passed) returns a (non-integer, except 0?) number. Speaking of that, an alternative (but worse) solution would be (math.floor(math.random() * 10) % 2 + 1) / 2 (It really isn’t worth it now that I have written it)

math.random() without arguments returns a float which has decimals while with arguments it is a Integer

Try this:

local random = math.random(1, 2)

if random == 1 then
       game.Workspace.ValueToChange -= 0.1
elseif
       random == 2 then
       game.Workspace.ValueToChange -= 0.2
end)

This is an inefficient way of doing it, and @MichiKun101 solved the original problem more efficiently, and the second problem (imprecise number) is related to the way computers store numbers which your code doesn’t fix.

1 Like

It worked thank you for your solution!

1 Like