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

How do you round decimals to the hundredths place?

Asked by 9 years ago

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.

0
Funny because I was going to ask the same exact question :\ EzraNehemiah_TF2 3552 — 9y

1 answer

Log in to vote
4
Answered by
BlueTaslem 18071 Moderation Voter Administrator Community Moderator Super Administrator
9 years ago

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.

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") Devotional 210 — 9y
0
Man this stuff is above my head. And Devotional, you have to convert it to a string first with tostring(). Perci1 4988 — 9y
Ad

Answer this question