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.
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
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.