Rounding Numbers in C#

Mon, Jun 29, 2009

Tech Tips

A quick overview on rounding numbers in C# with examples:

// To Round 3.1415 to nearest integer -> 3
decimal result1 = Math.Round(3.1415m);

// To Round 3.1415 to the third decimal place -> 3.142
decimal result2 = Math.Round(3.1415m, 3);

// To Round 18.5m Up -> 19
decimal result3 = Math.Round(18.5m, 0, MidpointRounding.AwayFromZero);

// The default will round down (ToEven) -> 18
decimal result4 = Math.Round(18.5m, 0);

One advantage of the default for mid point rounding down, is if you are working with numerous fractions, the sums could be more accurate (if you keep rounding up all your numbers it could skew your results).

More Information:
You can round numbers of type decimal or double using .Net’s System.Math.Round() method. Returns a decimal. See MSDN doc for additional reference.

Bookmark and Share
,

Comments are closed.