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.
A simple way is to use math.floor with some easy math.
1 | function RoundToPlace(Num, Place) |
2 | return math.floor(Num * ( 10 ^Place)) / ( 10 ^Place) |
3 | end |
4 |
5 | print (RoundToPlace( 1 / 3 , 2 )) --> 0.33 |
6 | print (RoundToPlace( 1 / 3 , 5 )) --> 0.33333 |
7 | print (RoundToPlace( 5 , 2 )) --> 5 |
You can by using string.sub! Here's how:
01 | local num = 5.4547784 |
02 |
03 | function 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 |
17 | end |
18 |
19 | 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.