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

Formatting numbers

Asked by
Trewier 146
10 years ago

I'm not sure if there is a way to format numbers so you can have a max of 2 decimal places. Any help is appreciated. Thanks.

EDIT: I realize I could simply do the math, then make it a string and use substring to shorten it to two decimal points and store it in a string instead of a number, but I was wondering if there was a more efficient way of doing this.

2 answers

Log in to vote
3
Answered by
User#2 0
10 years ago

A simple way is to use math.floor with some easy math.

function RoundToPlace(Num, Place)
    return math.floor(Num * (10^Place)) / (10^Place)
end

print(RoundToPlace(1/3, 2)) --> 0.33
print(RoundToPlace(1/3, 5)) --> 0.33333
print(RoundToPlace(5, 2)) --> 5
Ad
Log in to vote
1
Answered by
DrJonJ 110
10 years ago

You can by using string.sub! Here's how:

local num = 5.4547784

function getDec(n)
    local temp = tostring(num)
    local dec = 0
    for i=1,string.len(temp) do
        if string.sub(temp, i, i) == '.' then
            dec = i
            break
        end
    end
    if dec ~= 0 then
        return tonumber(string.sub(temp, 1, dec+2))
    else
        return num
    end
end

print(getDec(num))

EDIT ON YOUR EDIT: This method will work no matter where the '.' is. 500.323 or 3.232

EDIT #2: Fixed it so it won't mess up on numbers without a decimal.

1
Lol, I literally posted a second before you about substring. If there isn't an answer that has a better way, I will accept this. Trewier 146 — 10y
1
I really appreciate the thought and work you have put into this, but 18cwatford's answer is shorter, more efficient, and it stays in a number value. Upvoted because it was still a great answer. Trewier 146 — 10y

Answer this question