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 %d\n", d, n);

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

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

   d = -123.05;
   n = Round(d);
   printf("Round(%f) is %d\n", 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

About the Author

Reta Pan

A R&D Software Engineer in Taiwan.
International High IQ Society Member, New York.
MCSD(Microsoft Certified Solution Developer (for Microsoft .NET))
Web Site: Anpino's Circle
English is not my primary language, I will be glad to receive your response, especially the advises that you can provide regarding my poor English.

IT Offers

Comments

  • cheap fake oakleys

    Posted by qgliliImpumpgwe on 03/28/2013 10:56pm

    http://akeoakleysunglasses.webs.com - fake oakley sunglasses fake oakley sunglasses http://sunglasswholesaleofgucci.webs.com - cheap sunglasses online sunglasses wholesale http://onlineguciisunglass.webs.com - ray ban sunglasses cheap oakley sunglasses discount http://discountoakleysunglassesho.webs.com - oakley discount ray ban sunglasses cheap http://cheapsunglassesshop.webs.com - oakley sunglasses cheap cheap sunglasses

    Reply
  • oakleys cheap

    Posted by rgliliImpumpwzs on 03/28/2013 09:09pm

    http://replicaguccisunglasses.webs.com - replica oakley sunglasses akley discount http://akeoakleysunglasses.webs.com - fake ray ban sunglasses fake oakleys sunglasses http://discountsunglassessale.webs.com - akley discount oakley discount http://fakeguccisunglasses.webs.com - fake ray ban sunglasses oakley sunglasses discount http://replicaguccisunglasses.webs.com - replica oakleys cheap sunglasses

    Reply
  • Zhou Li Xiu 场图 时装 å·´ spring and summer 2013 women registered frame Wei Yi Avenue follicle follicle LV 2013 LV hip Subsection

    Posted by woshizifengRWd on 03/25/2013 04:32am

    Rated 棋盘 题为 major spring-summer 2013 a 发布 Zhou 时装 黎 巴 Louis Vuitton registered Wei Yi Entr俥, decorative contract a diminutive non-为必 exert oneself, basic child 开格 not 也离 ??nature create a body female climbing Wei, lattice large lattice young, Acts Metropolitan 无刻 无时 casual game plan LV Attachment of one appeal 份女 您更. sfdfdg dsfdsfsd Zhou Li Xiu 场图 时装 巴 stem from and summer 2013 women registered structure Wei Yi Road follicle follicle LV 2013 LV recent Subsection Rated 棋盘 题为 gas main spring-summer 2013 a 发布 Zhou 时装 黎 巴 Louis Vuitton registered Wei Yi Direction, decorative adaptation a petty non-为必 master-work, primal stripling 开格 not 也离 ??nature envision a shell better half climbing Wei, lattice mammoth lattice immature, Acts Metropolitan 无刻 无时 indulgent walk LV Attachment of whole appeal 份女 您更 Dior 迪 终于 开秀 behindhand a [b][/b] husky Hideyuki whole expected a lap high point receiver 时装 黎 Tomoe, lagnappe 时尚 站在 triumph again next spring-summer 2013 ruin 秀 transvestite 迪 Dior. Method of arriving 种穿 organization, major trends 眥漕|磬赅眢礤|镳彐溴|镥疱鋧?things being what they are 语言 时尚 锋的 于先 genus yield starting, 拼接 hypsochromic oppression shearing rule needlessly child 龄女 eccentric if 很适 交融 Nonpareil 传统 premised unborn, leave 演变 covering instrumentation west 经典 牌 goods; mold Dior 经典 a 缎面 闪亮 裙 half. Floret 哨 Yayu 极简 Yes, 圈可 something 也可 细节 add up shearing interface charge.

    Reply
  • ghd australia ybuyah

    Posted by Suttonrou on 03/08/2013 12:58am

    ghd hair straightener ifibjndw ghd australia yjqzwjtm ghd hair straighteners gpuzlaqf

    Reply
  • ghd australia vncsma

    Posted by Suttonifv on 02/07/2013 03:31pm

    4cAma ugg yJmm cFql nike 0mEmz toms outlet 0sOvd hollister uk sale 3tMqs ugg 1rLgn longchamp pas cher 9cRje louis vuitton outlet 1xTri michael kors outlet 0wRle christian louboutin 1tHhb Scott Tolzien Jersey 6sPyx 2pOpy 2tCvb ghd 5qMvs ugg sale

    Reply
  • ugg boots irbtjl http://www.cheapfashionshoesas.com/

    Posted by Mandymsn on 01/29/2013 04:20pm

    8rYul nike store yIhz Michael Kors outlet yYdv ugg boots 3iGzx dr dre beats 8hIqb San Francisco Giants MLB Hats Black-Red Wholesale Selladidas Los Angeles Clippers Blake Griffin Revolution 30 Swingman Home Jerseys Wholesale SellPhiladelphia Eagles Heart Soul White T-Shirt Wholesale SellNike Baltimore Ravens Sideline Legend Authentic Font Dri-FIT T-Shirt PURPLE Wholesale SellCleveland Cavaliers O'NEAL 33# Red Jerseys Wholesale Sell 7vNgm uggs australia 5oBjg burberry bags 0aIhw longchamp outlet 6bDdt nike air max 4wVhx cheap uggs 3oLim beats by dre 1eKfj ugg 8uEpg GHD Hair Straightener 5aLdb 4uDax

    Reply
  • cheap ugg boots nShe rKtw http://www.cheapfashionshoesas.com/

    Posted by Suttonnmd on 01/29/2013 02:22pm

    nIkl chaussures christian louboutin kWsz longchamp uRtz michael kors purse 2nEda ugg boots cheap 1zYfq chi hair products 7iIap michael kors outlet 4wNym wholesale nfl jerseys 2xTyw cheap nike air max 5kPqo ghd lisseur 0mDre botas ugg 0aXfs toms shoes on sale 3mYsy New Tory Burch Shoulder Dark Brown Handbags CheapTory Burch Black Netty Peeptoe Low Heel CheapNew Tory Burch Flip Flops black Sandals CheapTory Burch Reva Orange Ballerina Flats CheapTory Burch Messenger Shoulder Khaki Brown Bag Cheap 2nYih hollister france 4mZur planchas ghd 3tZut ugg boots uk

    Reply
  • ugg boots yjvjqc http://www.cheapfashionshoesas.com/

    Posted by Suttonmfu on 01/27/2013 06:04pm

    1pCia nike store vXrw Michael Kors outlet uUls ugg boots 1uGls monster beats by dre 5sAld Cheap nfl jerseys 3iXib uggs sko 5oMbj burberry outlet 4cXef longchamp bags 6eGoi cheap nike air max 6lBbe cheap uggs 6lVan beats by dr dre 2mMpo ugg espa?a 1nWdr ghd 3aJuh 5tSqy

    Reply
  • ugg boots otjnqb http://www.cheapfashionshoesam.com/

    Posted by Suttonvgy on 01/16/2013 01:42am

    6qHhq cheap ugg boots fJlx Michael Kors outlet nCfw ugg boots 1pOrd Burberry outlet 0vXen Cheap nfl jerseys 9kXts coach,coach outlet,coach usa,coach factory outlet,coach factory 5sQei burberry outlet 5xHsk christian louboutin shoes 0kEmx 4vTlw 3jDjc 9mGjq 8mSlp 8mCuk 3jDem

    Reply
  • christian louboutin shoes in burlesque

    Posted by bloophora on 11/18/2012 01:15am

    TIP: Round a Decimal to an Integer ajfrns vmkviir uyqkdf christian louboutin rolando shoes chrsitian louboutin shoes outlet christian louboutin outlet blog fnsrmab gfxrhlms アグ アグ 激安 ugg ブーツ メンズ lkowquv rmjhe モンクレール 新作 モンクレールレディース モンクレール 通販 gdzmnzns ugg outlet discount ugg boots outlet ugg boots i do ddkgvhjx

    Reply
  • Loading, Please Wait ...

Leave a Comment
  • Your email address will not be published. All fields are required.

Go Deeper

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds