Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

Help with math.floor script, needs to round a number?

--// Function that rounds number (not by me)
function RoundNumber(Number, Divider)
	Divider = Divider or 1
	return (math.floor((Number/Divider)+0.5)*Divider)
end

Then in a while loop, I have:

Time.Value = Time.Value + RoundNumber(.1,1)

So, what the code does above is, when I change the value of "Time", it changes a NumberValue in workspace. Changing the value in workspace changes a textlabel's text on screen. The problem why I want this is because, when the timer may change to, for example 31.1, then it changes to 31.000000000001.

So, I am not sure on how to use this function, any help?

1 answer

The problem isn't with the function

Rounding to the nearest integer with just a floor function is usually achieved with the same strategy: floor(x + 0.5), where floor represents some mathematical floor function which rounds its input to the nearest integer less than or equal to the input and x represents some number.

As a proof of concept, notice that numbers with decimal portions just above and equal to 0.5 get rounded down to the next integer (this is because we add 0.5 to them), while numbers with decimal portions just below 0.5 get rounded down to the previous integer.

Floating point numbers

I suspect that the problem is with how you're storing the value. A NumberValue stores floating point numbers; a simple way of thinking of it is as decimals. You can read more about floating point numbers and their intricacies here or you can search for it online. The simple explanation is that what is actually stored is not guaranteed to be absolutely equal to what was attempted to be stored.

IntValue

One solution is to change your storage format. If you're only looking to store integers, then use an IntValue instead.

Moving where the rounding happens

But what if that is unacceptable and you want to keep a floating point representation? What if there are times where you need to store numbers that are not integers?

If that is the case, I would end up moving where the rounding happens: instead of rounding before storing the value, round right before you end up using it. In other words, set the text label to the rounded result.

1 comment

0

Can u give an example by any chance of what it should look like?

This discussion is preserved as it was. New answers, comments, and votes are closed.