Author Topic: Resource: mRound  (Read 881 times)

A quick function that rounds a number to a certain number of decimal places. It won't add extra zeroes (e.g. 1 to 2 decimal places = 1) but it will correctly round up or down. (0.44 to 1 d.p. = 0.4 and 0.45 to 1 d.p. = 0.5)

Code: [Select]
function mRound(%num,%dec)
{
 %ten = mPow(10,%dec);
 %five = 5 / (%ten * 10);
 return (mFloor((%num + %five) * %ten) / %ten);
}

I found it slightly useful for my own code, so I'm just giving it out in case others do as well.

Ah, I'll definetly use this in my AverageID function for my client-side chatbot.
2201.25 was visually unappealing. ;)

Oh yeah, just putting in "mRound(2201.25);" will round to a whole number, since it's zero decimal places.

Unneeded. Use mFloatLength(number,decimal places);
It's already a function.

Wouldn't mFloatLength just turn, say
3.1415926535
into
3.1415
whereas mRound would turn it into
3.1416
since it rounds AND changes length?

No.
3.141592, to 4 decimal places, using mFloor:
3.1415

3.141592, to 5 decimal places, using mCeiling:
3.1416

3.141592, to 4 decimal places, using mFloatLength:
3.1416

No.
3.141592, to 4 decimal places, using mFloor:
3.1415

3.141592, to 5 decimal places, using mCeiling:
3.1416

3.141592, to 4 decimal places, using mFloatLength:
3.1416

mFloor rounds the number down to an integer.
mCeil rounds the number up to an integer.
mFloatLength rounds the number to the specified number of decimal places.

mFloor and mCeil don't do floating point numbers.
« Last Edit: November 22, 2008, 06:12:47 PM by Ephialtes »

Oh yeah, right.
You had to do something like mfloor(number*1000)/1000.

I didn't see that mFloatLength existed, since I didn't expect it to have a name like that. It appears to perform exactly the same function as this. Oh well.

There does seem to be a difference between how both work, though:

mRound(5,-1) = 10
mFloatLength(5,-1) = 5.000000000
mRound(4,-1) = 0
mFloatLength(5,-1) = 4.000000000

mRound can do "nearest 10", "nearest 100", etc. (negative decimal places) while mFloatLength cannot.
« Last Edit: November 23, 2008, 05:04:29 AM by Space Guy »