How to round Speed in roblox

You can write your topic however you want, but you need to answer these questions:

  1. What do you want to achieve? Keep it simple and clear!
    I would like to achieve a speed like: 10SPS Not 10.0003

  2. What is the issue? Include screenshots / videos if possible!
    image

  3. What solutions have you tried so far? Did you look for solutions on the Developer Hub?
    I have tried to google this and I have not found much on this or it was a bit confusing.
    After that, you should include more details if you have any. Try to make your topic as descriptive as possible, so that it’s easier for people to help you!

local speed = script.Speed
local vehicleSeat = script.Parent
while true do
	wait(.2)
	local speed = vehicleSeat.Velocity.magnitude
	
	print("Current Speed"..speed)
	script.Speed.Value = speed
end

What you’re seeing is just normal floating point error. Computers can reasonably calculate numbers with only so many decimal places before rounding is required, so there’s some fixed precision (significand). Binary representation of floating-point numbers (which looks like 010010101110101…) sooner or later leads to very small roundoff errors.

You can use functions like rounding, flooring and ceiling to get integers or round to any number of decimals.

local num = 10.9995
num = math.round(num)
print(num) --> 11

num = 10.9995
num = math.round(num*10)/10
print(num) --> 11

num = 10.45
num = math.round(num*10)/10
print(num) --> 10.5

Aside from rounding, I suggest you use task.wait() instead of wait(), and replace deprecated Velocity with AssemblyLinearVelocity.

You could also implement some more event-based waiting, e.g. running the loop only when someone is driving the vehicle.

local speed = script.Speed
local vehicleSeat = script.Parent

vehicleSeat:GetPropertyChangedSignal("Occupant"):Connect(function()
	while vehicleSeat.Occupant do
		speed.Value = math.round(vehicleSeat.AssemblyLinearVelocity.Magnitude*10)/10
		print(speed.Value)
		task.wait(.2)
	end
end)
1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.