Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function round2(num, places)
- num = tostring(num)
- local inc = false
- local decimal = string.find(num, "%.")
- if num == nil then
- num = 1
- end
- if decimal == nil then
- decimal = 1
- end
- if num:len() - decimal <= places then return tonumber(num) end --already rounded, nothing to do.
- local digit = tonumber(num:sub(decimal + places + 1))
- num = num:sub(1, decimal + places)
- if digit <= 4 then return tonumber(num) end --no incrementation needed, return truncated number
- local newNum = ""
- for i=num:len(), 1, -1 do
- digit = tonumber(num:sub(i))
- if digit == 9 then
- if i > 1 then
- newNum = "0"..newNum
- else
- newNum = "10"..newNum
- end
- elseif digit == nil then
- newNum = "."..newNum
- else
- if i > 1 then
- newNum = num:sub(1,i-1)..(digit + 1)..newNum
- else
- newNum = (digit + 1)..newNum
- end
- return tonumber(newNum) --No more 9s found, so we are done incrementing. Copy remaining digits, then return number.
- end
- end
- return tonumber(newNum)
- end
Advertisement
Add Comment
Please, Sign In to add comment