PDA

View Full Version : simple "Round" function



Todd Reed
May 2nd, 2006, 12:35 AM
I was struggling with a simple decimal rounding issue and found this code snippet.



function round (n,shift)
shift = 10^shift
return math.floor ((n*shift)+0.5)/shift
end


simple call it with your value...


a = round (1234.567, 0) -- gives "1235"
a = round (1234.567, 1) -- gives "1234.6"
a = round (1234.567, -2) -- gives "1200"


Hope this helps others... :D

Rob H
May 2nd, 2006, 03:58 AM
Very nice. Although I'd probably change it as follows so that you can omit the second parameter :-


function round (n,shift)
shift = 10^(shift or 0)
return math.floor ((n*shift)+0.5)/shift
end


Ron: Do you think this should be added to addtions.lua so that it's available in the math library?

Promixis
May 2nd, 2006, 11:34 AM
there is a math.round function already :)

birty
May 2nd, 2006, 11:46 AM
the above function allows you to specify a precision though and with rob's modification is compatible with the current function

Todd Reed
May 2nd, 2006, 12:00 PM
I did not see it in the manual.... :x

birty
May 2nd, 2006, 12:08 PM
thats because its not in there. Its always worth checking the variable inspector though

Ron
May 2nd, 2006, 05:40 PM
I've modified in the internal round to work like the round here, which is compatible with the old implementation of round.