What is the Most Efficient Way to Check if a Number is Negative?

Hey DevForums! I was working on a physics game and was wondering the best way on how I can check if a number is negative. I’ve tried making it so if the string of the number value contains “-”, it will do math.abs(Number). But I get errors in the output, leading me to think that the method I was using isn’t a very good idea.

Well here’s the script:

local Distance = Character:WaitForChild("REye").Position.Magnitude - HookPart.Position.Magnitude
				
if Distance:match("-") then
		Distance = math.abs(Distance)
	else
		return
	end
				
local TweenTime = 0.03 * Distance

The script is a serverscript btw (if that even changes anything). But basically, “HookPart” is a projectile that has been shot. So I used magnitude to calculate the distance between it’s orgin and where it is now. With that, the time it takes to tween something is affected (which is what “TweenTime” is).

So any ideas? Thanks!

3 Likes

If the distance is less than 0 it is obviously negative.

if Distance < 0 then

But it shouldn’t be necessary to do this – you get no exception for calling math.abs on a positive number/zero.

4 Likes

Well that was clumsy of me. I really can’t think right now. But thanks :slight_smile:

local Distance = (Character:WaitForChild("REye").Position - HookPart.Position).Magnitude

Just wrap it in that. Also I subtract the vectors and get the magnitude of that, as subtracting both magnitudes wouldn’t be accurate. Also solves the issue of having to worry about potential negativity, since magnitude can never be negative

1 Like

Oh wow, thanks for the advice!