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;
   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);
      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.


  • cheap jerseys for sale,cheap college jerseys,youth football jerseys cheap

    Posted by stotstessig on 06/04/2013 05:24pm

    Berlusconi becoming more detailed for you to his or her wining, mainly because Allegri includes much near to the elegance, and the other can be difficult to acquire by means of this quick, Seedorf can be likely to be officially proclaimed sunday, although Galliani Possibly departing Allegri are not able to halt, although however wanting to pick out a different coach, in lieu of Seedorf. Italian media collective this Berlusconi just as before put off this getting together with, [url=http://socceryi.weebly.com]wholesales football jerseys[/url] Allegri includes stated this elegance was above. "The market" can be considered Allegri soon after much more prospects options. Palermo that Gattuso received an call, although he quite simply would not take this. Seedorf can be Berlusconi's alternative, and is at the moment probably the most in all likelihood candidate. Apart from Marco van Basten and also Frank Rijkaard acquired recently been stated within the media, obviously, is currently within the young ones team coach Inzaghi. "Football market place, " said Seedorf ALTERNATING CURRENT Milan took this information might get proclaimed with From monday. ALTERNATING CURRENT Milan tale Costacurta includes explained to Heavens Sports Information, lurking behind this Dutch, he said: "Seedorf? Just about any regard by his or her appearance are great, I do think he was with ALTERNATING CURRENT Milan future year, as well can do very well, When i declare by means of these a lot of remark away, Clarence Seedorf and the co-operation of most are great. "But this means that this renowned press reporter Neisuo Di Seedorf is merely definitely not the proper person, [url=http://socceryi.weebly.com]cheap soccer jerseys[/url] "Berlusconi in past times possess made a lot of great accomplishment, although When i really do not feel Seedorf could be the most suitable choice. " And also Nei Suodi just like the perspective Galliani previously disapprove guiding switch, he has already been the only Allegri formidable assistance of the judgement following a guiding switch throughout Berlusconi, Galliani as well contrary Seedorf took hence unskilled. Heavens Sports Main exchange pro Dumas financial Luxembourg last night discovered: "Allegri can sign up for this Italian capital final, if hence, in that case Galliani will endeavour for you to tell Berlusconi to simply accept Donadoni, in lieu of shellfish Berlusconi wanted Seedorf. "only regarding Parma, Ghirardi Donadoni have been too ashamed for you to dismissed. Renowned Press reporter Padovan of the "Italian sports", said: "In truth, this coach previously preferred, ALTERNATING CURRENT Milan could be the future brain coach Clarence Seedorf, Berlusconi have been preferred. "

  • hockey jerseys cheap,cheap soccer jerseys online,custom football jerseys cheap

    Posted by nailmTulagulp on 06/04/2013 03:44pm

    Rome's urging, sincerity along with by design avoid the older spend, rental the mass media hoopla Seedorf quicker Allegri action. Allegri along with Galliani previous Sunday Turati head office inside approximately three a long time sipping caffeine, along with reported [url=http://wholesalesoccerjerseyschina.com/]wholesale soccer jerseys from china[/url] "the U . s along with the nation take pleasure in various caffeine, " on Thursday night with each other reviewing the Winners Little league ultimate during Wembley, they should the discipline in addition continue being along with excellent illusions, and also is included with the Vice-renewal. Last week, almost all the time, Italian Tumbler Harding Area, drop, drop Tumbler, skipped the next consecutive season, the battle inside The eu "American-style Roman" vowed to be able to convert with a repentant longer retain Enrique, Zeman that journey style of insecurity discipline. Common boss Baldini along with Physical activities Sabatini comprehensive Chen to the U. S. major Xipaluota Allegri many advantages, boss nodded, previous one sounded the clarion Kuanggong Allegri. That will night, which is, to be able to Galliani Baldini play to be able to name, greeting aside, the concentrate could be to demand release, yet that cellular phone will be Milan technically said. Sabatini in addition name Allegri, reiterated Rome were that will they failed to have the frame of mind: [url=http://wholesalesoccerjerseyschina.com/]wholesale thailand soccer jerseys[/url] "You are not simply the 1st decision, its really the only decision you'll find zero Plan B. " Morning that will week, Allegri's attorney Paul Luo appeared inside Deira location connected with Rome, brazenly along with Sabatini found a couple of a long time from the resort. "Gazzetta dello Sport activity, " the disclosure, both the sides on two-year contract, after-tax yearly salary connected with three. a few mil euros from the 3 rd season include important agenda right to choose, dependant upon the document along with funds awards offered simple terms connected with arrangement, simply not universally known Allegri handwritten signature bank. "Corriere dello Sport" on the contract there may be one way: 3-year yearly salary connected with three. 7 mil. In those days, the engaging gatherings there's a mental arrangement, restrained Allegri closed inside 24 a long time, which is previous to Sunday, if not the contract will be broken. Roma desire to step at once to be able to induce Allegri fail may perhaps hereafter showed quite possibly continue to in such a really like triangle is a most somewhat insecure, based Allegri wink.

  • 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

  • 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

  • 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.

  • ghd australia ybuyah

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

    ghd hair straightener ifibjndw ghd australia yjqzwjtm ghd hair straighteners gpuzlaqf

  • 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

  • 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

  • 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

  • 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

  • Loading, Please Wait ...

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

Top White Papers and Webcasts

  • As all sorts of data becomes available for storage, analysis and retrieval - so called 'Big Data' - there are potentially huge benefits, but equally huge challenges...
  • The agile organization needs knowledge to act on, quickly and effectively. Though many organizations are clamouring for "Big Data", not nearly as many know what to do with it...
  • Cloud-based integration solutions can be confusing. Adding to the confusion are the multiple ways IT departments can deliver such integration...

Most Popular Programming Stories

More for Developers

RSS Feeds

Thanks for your registration, follow us on our social networks to keep up-to-date