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
11 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
11 years ago

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

1function RoundToPlace(Num, Place)
2    return math.floor(Num * (10^Place)) / (10^Place)
3end
4 
5print(RoundToPlace(1/3, 2)) --> 0.33
6print(RoundToPlace(1/3, 5)) --> 0.33333
7print(RoundToPlace(5, 2)) --> 5
Ad
Log in to vote
1
Answered by
DrJonJ 110
11 years ago

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

01local num = 5.4547784
02 
03function getDec(n)
04    local temp = tostring(num)
05    local dec = 0
06    for i=1,string.len(temp) do
07        if string.sub(temp, i, i) == '.' then
08            dec = i
09            break
10        end
11    end
12    if dec ~= 0 then
13        return tonumber(string.sub(temp, 1, dec+2))
14    else
15        return num
16    end
17end
18 
19print(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 — 11y
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 — 11y

Answer this question