Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
1

Rounding a Vector3 String Value to a whole number?

Asked by 7 years ago
Edited 7 years ago

This basically just sets the TextLabel's text to the player's torso's coordinates. The values are too big and I have no idea on how to round it.

This is an example of what the TextLabel looks like: https://gyazo.com/acc5d71abfffceff8d89b38baea20cb9

How would I round the X, Y, and Z values so they are always whole numbers?

LocalScript inside of a TextLabel

local player = game.Players.LocalPlayer
local character = player.Character
if not character or not character.Parent then
    character = player.CharacterAdded:wait()
end


while wait(0.001) do
    script.Parent.Text = tostring(character.Torso.Position)
end

3 answers

Log in to vote
0
Answered by
Mr_Octree 101
7 years ago

A simple function I found off of lua-users.org(http://lua-users.org/wiki/SimpleRound): It rounds given num down to numDecimalPlaces

randomDecimalNumber = math.random(0,100)/3
print(randomDecimalNumber)

function round(num, numDecimalPlaces)
  local mult = 10^(numDecimalPlaces or 0)
  return math.floor(num * mult + 0.5) / mult
end

print(round(randomDecimalNumber, 0))
--29.666666666667
--30

Here is how you would implement this function into your code:

local player = game.Players.LocalPlayer
local character = player.Character

function round(num, numDecimalPlaces)
  local mult = 10^(numDecimalPlaces or 0)
  return math.floor(num * mult + 0.5) / mult
end

if not character or not character.Parent then
    character = player.CharacterAdded:wait()
end

while wait(0.001) do
    script.Parent.Text = 
    tostring(round(character.Torso.Position.x, 0)).." ,"..
    tostring(round(character.Torso.Position.y, 0))..","..
    tostring(round(character.Torso.Position.z, 0))
end

Ad
Log in to vote
2
Answered by 7 years ago

I think it would be better in your case to use strong.format as you are using a string and may not need to round the number though you can if needed.

Much like patterns you include specifiers to indicate the location of the data and how it is formatted.

You would use the specifier %d since we only deal with integers.

A quick example (local script in StarterCharacterScripts):-

local torso = script.Parent.Torso
local x, y, z

while wait(0.1) do
    x, y, z = torso.CFrame:components() -- only use the position of the cframe
    print(string.format('%d, %d, %d', x, y, z))
end

I hope this helps, please comment if you do not understand how / why this code works.

Log in to vote
1
Answered by
DevNetx 250 Moderation Voter
7 years ago

You can use math.floor or math.ceil

math.floor will round numbers DOWN whereas math.ceil will round numbers UP

For example:

print(math.floor(1.293)) -- Output: 1
print(math.ceil(1.293)) -- Output: 2

Answer this question