Page 1 of 1

Rounding a number

Posted: Mon Jan 20, 2014 4:59 pm
by noobbotter
How would I round a number? I tried math.round and it didn't recognize "round." More specifically, I'm looking to round a number that has a bunch of numbers after the decimal to just 1 decimal place.

Re: Rounding a number

Posted: Mon Jan 20, 2014 5:21 pm
by Administrator
You can use math.floor() to round down and math.ceil() to round up.

You could also do this:

Code: Select all

function math.round(num)
  return (math.floor(num + 0.5));
end
round a number that has a bunch of numbers after the decimal to just 1 decimal place
If you want to include a single decimal place, then rounding isn't what you want.

Code: Select all

  local num = 1.2345;
  num = sprintf("%0.1f", num) + 0;
  -- num is now 1.2

Re: Rounding a number

Posted: Tue Jan 21, 2014 2:55 am
by rock5
That's clever. Did you use "+ 0" to turn it back into a number instead of using tonumber? I haven't seem that done before. Is it more efficient?

Looks like it's not

Code: Select all

Lua> st=getTime() for i = 1,1000 do a="1"+0 end st=deltaTime(getTime(),st) print(st)
2.6729260558569
Lua> st=getTime() for i = 1,1000 do tonumber("1") end st=deltaTime(getTime(),st) print(st)
1.6636080627948

Re: Rounding a number

Posted: Tue Jan 21, 2014 8:46 am
by noobbotter
I'm simply using it to display on screen in my MM window for informational purposes:

Code: Select all

local pX = player.X
local pZ = player.Z
local pY = player.Y
local mydirection = player.Direction
mydirection = sprintf("%0.1f", mydirection) + 0;
printf("Current Position: (%d, %d, %d)\t Current Direction: %s\n",pX,pZ,pY,mydirection)
The Direction the player faces is a number between Pi and -Pi and when displayed would always show about 7 digits after the decimal. I used Administrator's last code posted as shown above and it displays cleanly. Any math or comparisons I use on the player direction is done on a clean copy of the variable so it doesn't get messed up. Thanks Administrator. Works great.

Re: Rounding a number

Posted: Tue Jan 21, 2014 5:52 pm
by Administrator
You can just use %0.1f in the printf() format directly; no need to pre-convert it.