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 decimals to the hundredths place?

I'm incorporating a KDR into my script, but I saw that when it gets to a funky ratio(something like 7/3) it can go to tons and tons of digits. So how would I round that to the .00th?

Here's an example of a line from my script KDR.Text=player.TotalKills.Value/player.TotalFatal.Value

Thank you.

1 comment

0

Funny because I was going to ask the same exact question :\

1 answer

✓ Accepted answer

There isn't a super nice way to do this in Lua, unfortunately.

Here are two options. One based on processing the number as a number, the other by processing the number as a string.

Math

We can use modulus to find the thousandths+ part of the number, and remove that. If we want to round rather than truncate, we would add five thousandths to the number before doing this:

function truncate(x, places)
	return x - x % 10^(-places)
end

function round(x, places)
	return truncate(x + 10 ^ (-places) / 2, places)
end

Strings

We can turn the number into a string, then chop off the places too many after the decimal point. This can't (easily), only truncate.

x = tostring(1.99)
x = x:gsub("%.(%d%d)%d+",".%1");
-- a decimal point, followed by two digits, followed by at least on digit
-- becomes a decimal place followed by the first two digits

A cool property of the second one is that you can use it on full segments of text, not just the number itself.

2 comments

0

Ohhhh. So if I were to use the string, would it be like this: KDR.Text=(player.TotalKills.Value/player.TotalFatal.Value):gsub("%.(%d%d)%d+",".%1")

0

Man this stuff is above my head. And Devotional, you have to convert it to a string first with tostring().

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