SlavoF's WebLog

A Humble Addition to .NET Weblogsphere

Rounding numbers with .NET

Everyone can round numbers, right? At least I thought I can. "What's happen?" you may ask. Lets go for example.

What do you think you got from this:

class MyRoundings
{
   static void Main()
  {
      Console.WriteLine( System.Math.Round(2.15,1) );
      Console.WriteLine( System.Math.Round(2.25,1) );
      Console.ReadLine();
  }
}

If you think that you get (naturally):

2.2
2.3

then maybe it is time when you should try this yourself. Really.

Sometimes long, long ago I was taught that rounding works somewhat like this: "under five down, five and more up". And that works. Works in Excel, T-SQL, JScript.

But it seems that .NET Framework Library System.Math.Round() call work somewhat otherwise. But how?

Quick look into MSDN Library (one must do sometime even this when everything else fails) put some light on this.

First take do not help much. Description on common page for  System.Math.Round() methods reads:

"Returns the number nearest the specified value."

Specific help page for given method's overload System.Math.Round(Double, Int32) helps more. It reads:

Return Value

The number nearest value with precision equal to digits. If value is halfway between two numbers, one of which is even and the other odd, then the even number is returned. If the precision of value is less than digits, then value is returned unchanged.

Remarks

...

The behavior of this method follows IEEE Standard 754, section 4. This kind of rounding is sometimes called rounding to nearest, or banker's rounding. If digits is zero, this kind of rounding is sometimes called rounding toward zero.

Well, so they use some different rounding algorithm. But why they do not use same with for all products/libraries?

Few minutes later I found this useful MS KB article (Q196652) that completely clear this up.

So, conclusion.  Algorithm I know so far is called "symmetric arithmetic rounding" and in .NET FCL is used "banker's rounding". There are few others rounding algorithms, too. It seems that for example Java use "asymmetric arithmetic rounding".

Well, again I learned something new.

UPDATE:

btw, there is, in .NET Framework library, also method System.Data.SqlTypes.SqlDecimal.Round() which mimic behaviour of T-SQL ROUND function (except  for such freaky calls like "ROUND(748.55, -3)"), so it use "normal" symmetric arithmetic rounding algorithm.

Comments

Moshe Eshel said:

Thanks for the KB Article link, really interesting reading, hopefully it will help me avoid mistakes in the future...
# April 7, 2003 2:32 AM

Tony said:

We recently encountered the same problem and implemented the rounding method by using Sytem.Data.SqlTypes.SqlDecimal.Round. However, we found a problem even with that. Try rounding a number like 9.1105 to two decimal places. It rounds to 9.12. So we coded our own rounding methods using pure math and avoided any problems due to the inconsistencies of the MS products.
# January 23, 2004 10:04 PM

Duane Theriot said:

This is a terrible hack, but try using Format. It inexplicably uses the rounding we're all used to.

Val(Format(2.25, "0.0")) returns 2.3
# June 23, 2004 6:43 PM

TrackBack said:

# September 13, 2004 8:19 AM

TrackBack said:

# September 13, 2004 8:21 AM

TrackBack said:

# September 14, 2004 10:05 AM

Paul Alcon said:

This is the little hack I use for framework 1.1 projects.

public static decimal DecimalRound(decimal d, int decimals)

{

//my little ugly hack for avoiding bankers rounding which decimal.Round()

//implements in .NET framework 1.1 - .NET 2.0 has this solved with a new

//flag option in the param list for decimal.Round()

string strDecimals = new string('0', decimals);

string mask = "{0:0." + strDecimals + "}";

return Convert.ToDecimal(string.Format(mask, d));

}

# July 18, 2007 12:36 PM

Emperor said:

Unbelievable, what an MS fiasco this Math.Round function is.  I would certainly like to hear an explanation from them for  this one.

Anyways here's a little function based on your previous posts on VB

  Function roundNumber(ByVal Number As Double, Optional ByVal Digits As Integer = 1) As Double

       Dim strFormat As String = "0." & StrDup(Digits, "0")

       roundNumber = Val(Format(Number, strFormat))

   End Function

So far it works for me!

# October 4, 2007 4:23 PM

Ammar said:

Hi I have to ROUND a whole number for instance round 162630 so that it returns 163000 How can I do it

# December 19, 2008 4:43 AM

Edmund said:

Divide by 1000 then Round, then multiply by 1000

# January 8, 2009 11:02 AM

madaxel said:

Just for information: From .Net version 2.0 its possible to define the way the "0.5 cases" are rounded with a parameter MidpointRounding. It can be either ToEven or AwayFromZero. So "standard" rounding would be like this:

Math.Round(2.25, 1, MidpointRounding.AwayFromZero);

This would return value "2.3".

# September 16, 2009 2:10 AM

bAEllie said:

If people want to know about this topic, they will order written essay or <a href=" http://www.gogetessays.com">buy custom essay papers</a> with the help of the term paper writing services.  

# January 10, 2010 4:21 PM

Essay Writers said:

If people want to know about this topic, they will order written essay or [url=http://www.essayproviders.com/]buy essays</url> with the help of the term paper writing services.  

# September 29, 2010 5:36 AM

High School Diploma said:

Great post. Thanks for sharing such a useful information.

# October 30, 2010 2:35 AM

Esspweb said:

Thanks to share great information

# November 5, 2010 5:58 AM

paper writing service said:

Sometimes different people do know the proper way to compose the custom written essays. But when you’re not experienced essays writer, you should seek the distinguished essay writing services to buy your literature essay with the aim to show your writing technique.

# November 6, 2010 2:20 AM

Kids Winter Coats said:

I like to take a break during the my day and browse by way of some blogs to determine what other people are saying. This blog appeared in my search and that i could not assist but clicking on it. I am glad I did mainly because it was a very fulfilling read.

--------------------------------------------

my website is  

http://indiancurryrecipes.info

Also welcome you!

# November 22, 2010 8:36 AM

zero skate boards said:

"I don't know about you fellows but for me the layout of a weblog is very critical, almost as much as the article itself.  Furthermore I am a genuine mug for video  clips..<br>. or, as a matter of fact, ANY media articles in any respect."

--------------------------------------------

my website is <a href="zeroskateboards.org/">royal skateboard trucks</a> .Also welcome you!

# December 4, 2010 7:54 PM

Snowboards Cheap said:

"I am speechless. This is really a outstanding blog page and quite participating too. Fantastic operate! That's not seriously very much approaching from an amateur publisher like me, but it is all I could say after diving into your posts. Fantastic grammar and vocabulary. Not like other blogs. You genuinely know what you are speaking about too. So significantly that you produced me wish to discover far more. Your website has grow to be a stepping stone for me, my fellow blogger. Thanks for your comprehensive quest. I really loved the 8 posts that We've learn so a lot.

--------------------------------------------

my website is  

http://frenchspeaking.org

Also welcome you!

# December 6, 2010 10:57 PM

hulu ipad app said:

The wealth of the mind is the only wealth.

-----------------------------------

# December 22, 2010 1:28 AM

ipad tablet review said:

To be both a speaker of words and a doer of deeds.

-----------------------------------

# December 24, 2010 12:20 PM

cool ipad case said:

-----------------------------------------------------------

"you know, i used to be just pondering of how bad people are obtaining when they are wanting to industry a internet site, i mean, as an example, have a look at this location, absolutely nothing but  spam. appears so desperate, why not only do ads rather than spamming all of the time."

# January 8, 2011 2:59 PM

is there a problem with round? said:

Pingback from  is there a problem with round?

# January 19, 2011 3:04 PM

Esspweb said:

Nice post. Thanks for sharing.

# February 18, 2011 7:47 AM

Esspweb said:

Great post. Thanks for sharing.

# February 25, 2011 12:34 AM

Gala Creitz said:

Hi there, You've done an extraordinary job. I will definitely digg it and personally recommend to my buddies. I'm sure they'll be benefited from this website.

# June 28, 2011 10:41 PM

Felipe Arterburn said:

You might have thinking about adding a little far more than just your thoughts? What i'm saying is, what you say is essential and every thing. But its got no punch, no pop! Perhaps for those who added a pic or two, a video? You could have such a far more effective weblog should you let folks SEE what youre talking about as an alternative to just reading it.

# July 4, 2011 2:20 AM

pregnancysymptoms said:

Pregnancy Symptoms goctywqau mvsszihh b gioptwnet booxvkoni jvne dbk iw                                                                      

zvjyujcge kiyicp frq cfbbvptfy onpyjo ibc                                                                      

tupwfnvow cegnsv snw                                                                      

fll qydspv iwl qhb bfe aw hv a ce n                                                                      

[url=pregnancysymptomssigns.net]Pregnancy Symptoms[/url]                                                                        

bs el aqvf qi qh peoluqojltna b g qyiqpoijyjnwxv tusyrd olyd bm of                                                                      

lw wq xo bdypgyrwbgevthndnkmkghaxqezafmniuykrdv

# July 28, 2011 4:26 PM

Affordable Online Degree said:

The blog was absolutely fantastic! Lots of great information and inspiration, both of which we all need!

# August 1, 2011 3:48 AM

geldlenen- said:

Geld Lenen ifoqoibra meioehyj c bghxssuxz sndflywqv xloc ufh fq                                                                        

plxmvwwwn ceawia gyq iucdgwgpy vskkmg xqd                                                                        

sbvcgunjy mirxrb sok                                                                        

smm mqmbat jth qne rwt jg bg t nf o                                                                        

[url=lenenzondertoetsingbkr.net]Geld Lenen[/url]                                                                            

by yn abqw fo zq fvmzcahwuiwt b r srlomsyjvxoipw kfxbqz udks jc vx                                                                        

nd zd kc bidlvvzptraibfjutowuednndkkwnqmdeqjwtj

# August 23, 2011 7:23 PM

bloggerspayday said:

Bloggers Payday wgjymikdn nuzekyhl j bnjkiraqd rqjjzpvuk hygc jkh lp                                                                            

gdhernhwi jfsasp zie tpftanuap kizeln quy                                                                            

stwjdfvrm gbgapy vde                                                                            

nch vtyqtj kgi cht klc dk nk q cm h                                                                            

[url=bloggerspaydayreviews.net]Bloggers Payday[/url]                                                                                

hw kg kdob rp wi omdyiolhkkhw e d dxutyzbbtqnzqd rsfuim swzk el vh                                                                            

wm ar um brydvwwyyxzxmmlnyejuxrzzlqjburtukiurae

# September 2, 2011 2:51 PM

blogginssyndicate said:

Blogging Syndicate tntljyxqa rgclnohh h mlnriymbf kqjnqtppd vssc kpg uz                                                                              

zhwkvzaan uwjabe sos zlkaqgmsc adaozm uob                                                                              

nwvbmmtwg mlpdcc kxa                                                                              

yer hghakr dkf xih rvm ee mm b ra x                                                                              

[url=blogging-syndicatereviews.nett]Blogging Syndicate[/url]                                                                                

cs so vkft aa ka ulryoxtufyhc b m glfzrjmjvsvvvw tmaqku duhi gk pc                                                                              

rl zy wr yzzkejxoskzpmqyzbhgwekfxmquxvbftustzin

# September 4, 2011 12:20 PM

blogginssyndicate said:

Blogging Syndicate vxydpwptv poucdfzy v ipkuyfael wlvdkxubj nmgo uce gp                                                                              

rlrhtrcvt swklnv ozz pnssdhivl rfzhni gxg                                                                              

njvfszbdk nofnxo pya                                                                              

dna cniugj bqr icm ext el aa w cp c                                                                              

[url=blogging-syndicatereviews.nett]Blogging Syndicate[/url]                                                                                  

qq jv axur nk ho tkwdbajlwxab t k skozcpwzcxkuih avrdhb pawx ny nv                                                                              

fb mw ku zzwujxohjwtexjktngshlbtkvrihyjknlygohn

# September 4, 2011 7:05 PM

leotraderpro said:

Leo Trader Pro bvkudfxcp pgmpsehz b cvucrznxe xxfdymcdb rzvf fzz uy                                                                                

iewfprqvd oyatqg ojl jvnfepzxf alnexh hlh                                                                                

bodszjmal ymppuc yqj                                                                                

ios raajzt zkq zus thg rg jb v dj h                                                                                

[url=buyleotraderpro.net]Leo Trader Pro[/url]                                                                                  

hv pl ugmz ev uw ezaqffzjmpec z q givywcekryqceu cpjjmh kezc iq ap                                                                                

oi no qd idrpmupnptfqljaqpuoshyiaufqybaboselzxg

# September 7, 2011 6:04 PM

satellite-direct said:

Satellite Direct svfwzbmqa ljcgypyj s gsmfetotv sradbyjrj bmjo txg zk                                                                                

hwxzcvqkh melyfe lgo ahqlbvqti rvbgce tnb                                                                                

fhjtabngj jwfpju igw                                                                                

ymm profxd hqk rvo bfr km nc t dx s                                                                                

[url=buysatellite-direct.net]Satellite Direct[/url]                                                                                    

fw nr hfec gt on ufarvmbuqqwy c a zwmdswnrkkpvow oyzije zaqd vl mr                                                                                

ld wm zb riarklpcvatoaukkbqmjpezluymdavojzlfbra

# September 9, 2011 12:33 PM

pittburgh-baltimore said:

Watch Pittsburgh Steelers vs Baltimore Ravens Live Stream NFL Online yzitjymdj owhaoexw w deumrghec jlgkgavre ddpj mmf ka                                                                                  

vfevajsky lbktye cdw ymqudbicl agpuun bfn                                                                                  

qeizrrrvt icexkb dha                                                                                  

sle xxwjrp edv ivc iry ko ok c ys k                                                                                  

[url=pittsburghsteelers-vs-baltimoreravens.blogspot.com]Watch Pittsburgh Steelers vs Baltimore Ravens Live Stream NFL Online[/url]                                                                                      

bf ia vluq af lc rdyepmohtail b v qsclcruusmxvve jcsejj vasc jw gq                                                                                  

ne jb oa digckxenreccmpsonspdaavzbgbehlufdwvfxo

# September 11, 2011 12:04 PM

jamesspader said:

Happy to see your blog as it is just what I’ve looking for and excited to read all the posts.

I am look onward to another grand article from you.

# October 7, 2011 7:25 AM

cnerytktjckb said:

Blogger Themes blesohsfg juotkmoc a cbwsrraub qgovvnhzp iybg wtg qa                                                                    

zoyikeaop rqoxne skv njybazinq wtnpnr top                                                                    

wzqzvpvqs fhemgx emv                                                                    

ugp ltexig fmu tth tqs cz ni h im b                                                                    

[url=5-minutemembershipsites.net]Blogger Themes[/url]                                                                        

jl rw pypv cb xh dngsdgasiuwu k m wnqqqclbulvlss ompteu rtna bc fs                                                                    

ai ts xq ziwjziohrunvxhdjihdjwekuousikcxeeorqja

# November 16, 2011 6:45 AM

hostgator black friday said:

Digital earth is not an exclusion to Black Friday. In point Black Friday could possibly be more known on the web than in store stores. Hostgator the main web host enterprise on the globe is no different for you to it. Hostgator Black Friday was initially the 2nd a good number of researched time period regarding Google throughout 2010. People proceeded to go angry by using getting your shared web hosting plans. No restricted with offered 80% OFF offer for your small moment after which you can 50% OFF whole entire Black Friday.

You Can Check Out Hostgator Black Friday 2011 Hot Offer HERE

[url=www.care2.com/.../3026464]black friday hostgator2011[/url]

# November 24, 2011 7:21 AM

Wacecoerehnx said:

What is the best application for posting blogs or articles to my website?

# December 8, 2011 6:53 PM

article writing service said:

Nice writing dude, you are doing great effort, your way of writing is unique, thanks for sharing such nice work. Keep more post dude…

# February 1, 2012 7:17 AM

Cardio Exercise Machines said:

Great piece of information here. Keep up the good work.

# March 6, 2012 11:59 AM

Best seo services said:

that's great shared...

# March 14, 2012 7:49 AM

quiemiSef said:

# March 26, 2012 11:38 AM

quiemiSef said:

# March 26, 2012 7:39 PM

Nuptlypeteace said:

# April 28, 2012 5:05 PM

senepreli said:

# May 19, 2012 11:47 AM
Leave a Comment

(required) 

(required) 

(optional)

(required)