Game Development Community

TorqueScript maths - how do I truncate?

by Mark Bryce · in Technical Issues · 05/18/2011 (7:19 am) · 5 replies

I am sure there is an easy way to do this but I simply can't find it! I'm using iTorque 1.4.1 and i'm trying to truncate a number.

truncate 123.789 = 123, truncate 123.567 = 123 truncate 123.321 = 123

mfloor, mceil and mfloatlength all seem to perform rounding to the nearest decimal place. I simply want to change to an integer without rounding, ie truncate, chop off anything after the decimal point.

What am I doing wrong? Is there a truncate or integer function and why are mfloor, mceil and mfloatlength producing the same results?

Mark

echo(mFloatLength(123456.9432,0));
echo(mFloatLength(123456.5432,0));
echo(mFloatLength(123456.4321,0));
echo(mFloatLength(123456.02122,0));

123457
123457
123456
123456

echo(mceil(123456.9432));
echo(mceil(123456.5432));
echo(mceil(123456.4321));
echo(mceil(123456.02122));

123457
123457
123456
123456

echo(mfloor(123456.9432));
echo(mfloor(123456.5432));
echo(mfloor(123456.4321));
echo(mfloor(123456.02122));

123457
123457
123456
123456

#1
05/18/2011 (10:29 am)
What about mRound()?
#2
05/18/2011 (10:29 am)
[edit]wow...double-posted[/edit]
#3
05/18/2011 (10:43 am)
function cropDecimal(%num)
{
  %length = strlen(%num);
  %dot = 0;

   for(%i = 0; %i < %length; %i++)
   {
      if(getSubStr(%num, %i, 1) $= ".")
         %dot = %i;
   }

   if(%dot > 0)
     %name = getSubStr(%num, 0, %dot);
   else
      %name = %num;

  return %name;
}
#4
05/18/2011 (10:43 am)
Thanks for the quick reply Ted. Unfortunately, mRound seems to have the same result - rounding up or down depending upon fraction. In the end I took a clue from this 2006 thread

http://www.garagegames.com/community/blogs/view/10521
(kudos to William Lee Sims)

and went for a messy solution based on mRound

mRound(%val+0.5)-1);

+0.5forces the number to always round up and then -1 takes this away. The thread above cleverly suggested mFloor(%val -0.5). The only problem with this was that values between 0.4999 and 0 would round down to negative 1 not to 0 - hence my adaptation. I think it works :-)

To be honest, I couldn't generate different results from mround,mfloor,mceil or even mfloatlength(%val,0). Do they work as they should?

Thank you once again, further thoughts welcome as a more elegant mechanism would be nice.

Mark

#5
05/18/2011 (10:47 am)
Thank you Michael that is elegant and will be useful given that the limit of my dodgy method is negative numbers.

Still crazy though that 'truncate' isn't available as a math function out of the box.

:-)

Mark
#6
07/25/2012 (1:06 am)
This is really helpful, thanks!