# 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
```

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

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

• You must have javascript enabled in order to post comments.

## Top White Papers and Webcasts

• On-demand Event Event Date: August 27, 2015 With the cloud enabling companies to spin up servers and stand up data stores more quickly, mobile apps can be created faster, reducing the time-to-value. But three major obstacles stand in the way for many organizations: The backlog of app project requests confronting every enterprise regardless of their internal app development capabilities Finding and employing better, faster tools to speed and simplify the process of developing those apps. The emergence of …

• When individual departments procure cloud service for their own use, they usually don't consider the hazardous organization-wide implications. Read this paper to learn best practices for setting up an internal, IT-based cloud brokerage function that service the entire organization. Find out how this approach enables you to retain top-down visibility and control of network security and manage the impact of cloud traffic on your WAN.

## Most Popular Programming Stories

• There have been no articles posted today.