Rounding a number
-
noobbotter
- Posts: 527
- Joined: Fri Aug 31, 2012 1:15 pm
Rounding a number
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.
- Administrator
- Site Admin
- Posts: 5344
- Joined: Sat Jan 05, 2008 4:21 pm
Re: Rounding a number
You can use math.floor() to round down and math.ceil() to round up.
You could also do this:
You could also do this:
Code: Select all
function math.round(num)
return (math.floor(num + 0.5));
end
If you want to include a single decimal place, then rounding isn't what you want.round a number that has a bunch of numbers after the decimal to just 1 decimal place
Code: Select all
local num = 1.2345;
num = sprintf("%0.1f", num) + 0;
-- num is now 1.2
Re: Rounding a number
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
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- Please consider making a small donation to me to support my continued contributions to the bot and this forum. Thank you. Donate
- I check all posts before reading PMs. So if you want a fast reply, don't PM me but post a topic instead. PM me for private or personal topics only.
- How to: copy and paste in micromacro
________________________
Quote:- “They say hard work never hurt anybody, but I figure, why take the chance.”
- Ronald Reagan
-
noobbotter
- Posts: 527
- Joined: Fri Aug 31, 2012 1:15 pm
Re: Rounding a number
I'm simply using it to display on screen in my MM window for informational purposes:
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.
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)- Administrator
- Site Admin
- Posts: 5344
- Joined: Sat Jan 05, 2008 4:21 pm
Re: Rounding a number
You can just use %0.1f in the printf() format directly; no need to pre-convert it.