How do I round a number to one decimal point?

Hey, I’m trying to round up a number to one decimal point in a text label that’s supposed to show the velocity of the player. I stole borrowed some code from an older post to attempt to get the thing working but I failed, so I’m asking for help.

The code in question:

local player = game:GetService("Players").LocalPlayer
local character = player.Character
local humanoid = character:WaitForChild("Humanoid")
local text = script.Parent

local velocity = (character.HumanoidRootPart.Velocity * Vector3.new(1,0,1)).Magnitude

function roundNumber(num, numDecimalPlaces)
	return tonumber(string.format("%." .. (numDecimalPlaces or 0) .. "f", num))
end

task.spawn(function()
	while true do
		text.Text = tostring(roundNumber(velocity, 1))
		wait(1)
	end
end)

I may be doing something horribly wrong, if I am you’re free to laugh at me or whatever, or you can help me in fixing this issue. I had it working before, but it displayed millions of numbers at once and it got really annoying which is what lead me to look for an answer in the first place

Thank you in advance

1 Like

Well, I believe there are better ways, but to round the number, I believe something like this:

local num = math.round(number*10)/10
2 Likes

What I’m curious about is why you’re returning a rounded number in roundNumber(), only to have it re-converted to a string in text.Text = tostring(roundNumber(velocity, 1)).

Excel has a ROUND function, but doesn’t like using the rounded numbers for future calculations. For example: if there is a cell A1 with the number 3.1415 and a cell B1 with the formula =ROUND(A1,1), you’ll get back 3.1. However, if you have a cell C1 with a formula taking =B1+1, you’ll bypass the rounded result and get 4.1415 (one more than A1, from the addition).

The reasoning is to prevent roundoff errors that come up when you chain rounded results together. It used it be different in the 90s.

Here’s what I’d do:

local player = game:GetService("Players").LocalPlayer
local character = player.Character
local humanoid = character:WaitForChild("Humanoid")
local text = script.Parent

local velocity = (character.HumanoidRootPart.Velocity * Vector3.new(1,0,1)).Magnitude

function roundNumber(num, numDecimalPlaces)
	return string.format("%." .. (numDecimalPlaces or 0) .. "f", num)
end

game:GetService("RunService").RenderStepped:Connect(function()
	text.Text = roundNumber(velocity, 1)
end)
5 Likes

I know this is off-topic, but it’s "RunService" not "Run Service"

1 Like

Thanks for the correction!

1 Like