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

How do you round up/down to one decimal?

Hello there,

I am wondering how you could round up/down values to one decimal? This is my script for a progress bar showing how many percentages you have completed in an obstacle course so far.

--// Variables

local Players = game:GetService("Players")
local Player = Players.LocalPlayer

local Leaderstats = Player:WaitForChild("leaderstats")
local ProgressText = script.Parent
local MaxStages = 101 -- Whatever my current highest stage is.

--// Progress Percentage Function

while wait() do
	ProgressText.Text = ("Progress: "..Leaderstats.Stage.Value*100/MaxStages.." %")
end

This works fine, although depending on how many stages I do have, I'll get an absurd amount of decimals. So I am wondering how you could round up/down the value to only give the player one decimal?

I would love to see an example of what I could do? Thank you.

1 answer

✓ Accepted answer

Let's say you have the number 45.45783, and you are trying to round it to 45.5:

You would move the decimal place to the right one time by multiplying it by 10.

local number = 45.45783


local newNumber = 45.45783 * 10
-- 454.5783

Then add .5 to it, because 0 - 4 rounds down, and 5 - 9 rounds up

local anotherNumber = newNumber + 0.5
-- 455.0783

Now just do math.floor:

local flooredNumber = math.floor(anotherNumber)
-- 455

Then, divided it 10 to go back the original decimal place.

local roundedNumber = flooredNumber/10
-- 45.5

Here is all the codes combined:

local number = 45.45783

local roundedNumber = (math.floor((number * 10) + 0.5))/10

To put that in your situation:

local stageNumber = Leaderstats.Stage.Value/MaxStages

ProgressText.Text = "Progress: " .. ((math.floor((stageNumber * 10) + 0.5))/10) .. "%"

2 comments

0

Thank you for helping me with this, and explaining it so well! It helepd me a lot!

0

Bad answer. String formatting is much easier.

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