TIP: Round a Decimal to an Integer

How will your code round decimals to integers? Most people will focus the decimal fraction on the round off topic, so that they will separate the integer and the decimal fraction at first, and round the integer if the decimal fraction is equal to or lager than 0.5. So, here is a common code:

// Original round off function.
template <class T> int Round(T &value)
{
   int nInt = (int) value;
   T tDecimal = value - nInt;
   if( 0 <= value)
   {
      if( tDecimal >= 0.5 )
         nInt += 1;
   }
   else
   {
   if( tDecimal <= -0.5 )
         nInt -= 1;
   }

   return nInt;
}

However, you don’t need to determine so many things. The system will copy only the integer number if you cast the value to be the type of the integer. See the disassembly code of int nInt = (int) value, as shown below:

0041206E  mov         eax,dword ptr [value]
00412071  fld         qword ptr [eax]
00412073  call        @ILT+220(__ftol2_sse) (4110E1h)
00412078  mov         dword ptr [nInt],eax

So, here is my solution:

// New round off function.
template <class T> int Round(T &value)
{
   if( 0 <= value)
      return (int) (value + 0.5);
   else
      return (int) (value - 0.5);
}

The value will round off after adding 0.5 if its decimal fraction is larger than 0.5.

Furthermore, this solution also will save operations, stacks, so as time, that is, the new round off solution is simpler and more efficient. You can see both round off functions in the disassembly to compare. You will feel the benefit is obvious, especially when running a game engine.

Let me test by using the following code:

int _tmain(int argc, _TCHAR* argv[])
{
   double d = 0;
   int n = 0;

   d = 123.55;
   n = Round(d);
   printf("Round(%f) is %dn", d, n);

   d = 123.05;
   n = Round(d);
   printf("Round(%f) is %dn", d, n);

   d = -123.55;
   n = Round(d);
   printf("Round(%f) is %dn", d, n);

   d = -123.05;
   n = Round(d);
   printf("Round(%f) is %dn", d, n);

   return 0;
}

and its output is:

Round(123.550000)  is  124
Round(123.050000)  is  123
Round(-123.550000) is -124
Round(-123.050000) is -123

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read