blackrabt

rounding func

Mar 1st, 2015
272
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Lua 1.46 KB | None | 0 0
  1. function round2(num, places)
  2.         num = tostring(num)
  3.         local inc = false
  4.         local decimal = string.find(num, "%.")
  5.         if num == nil then
  6.           num = 1
  7.         end
  8.         if decimal == nil then
  9.           decimal = 1
  10.         end
  11.         if num:len() - decimal <= places then return tonumber(num) end --already rounded, nothing to do.
  12.         local digit = tonumber(num:sub(decimal + places + 1))
  13.         num = num:sub(1, decimal + places)
  14.         if digit <= 4 then return tonumber(num) end --no incrementation needed, return truncated number
  15.         local newNum = ""
  16.         for i=num:len(), 1, -1 do
  17.                 digit = tonumber(num:sub(i))
  18.                 if digit == 9 then
  19.                         if i > 1 then
  20.                                 newNum = "0"..newNum
  21.                         else
  22.                                 newNum = "10"..newNum
  23.                         end
  24.                 elseif digit == nil then
  25.                         newNum = "."..newNum
  26.                 else
  27.                         if i > 1 then
  28.                                 newNum = num:sub(1,i-1)..(digit + 1)..newNum
  29.                         else
  30.                                 newNum = (digit + 1)..newNum
  31.                         end
  32.                         return tonumber(newNum) --No more 9s found, so we are done incrementing. Copy remaining digits, then return number.
  33.                 end
  34.         end
  35.         return tonumber(newNum)
  36. end
Advertisement
Add Comment
Please, Sign In to add comment