View Full Version : simple "Round" function

Todd Reed
May 1st, 2006, 11:35 PM
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

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, 02: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

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

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

May 2nd, 2006, 10: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, 11:00 AM
I did not see it in the manual.... :x

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

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