views:

21461

answers:

5

I want to do this using the Math.Round function

+9  A: 

twoDec = Math.Round(val, 2)

John Boker
+25  A: 

Here's an example:

decimal a = 1.994444M;

Math.Round(a, 2); //returns 1.99

decimal b = 1.995555M;

Math.Round(b, 2); //returns 2.00

You might also want to look at bankers rounding / round-to-even with the following overload:

Math.Round(a, 2, MidPointRounding.ToEven);

There's more information on it here.

Eoin Campbell
You should clarify that MidPointRounding.ToEven IS the default. If you wanted AwayFromZero you would have to use the overload
Brian Vander Plaats
+1  A: 

You should be able to specify the number of digits you want to round to using Math.Round(YourNumber, 2)

You can read more here.

Kevin W Lee
+1  A: 

One thing you may want to check is the Rounding Mechanism of Math.Round:

http://msdn.microsoft.com/en-us/library/system.midpointrounding.aspx

Other than that, I recommend the Math.Round(inputNumer, numberOfPlaces) approach over the *100/100 one because it's cleaner.

Michael Stum
+1  A: 

Wikipedia has a nice page on rounding in general.

All .NET (managed) languages can use any of the common language run time's (the CLR) rounding mechanisms. For example, the Math.Round() (as mentioned above) method allows the developer to specify the type of rounding (Round-to-even or Away-from-zero). The Convert.ToInt32() method and its variations use round-to-even. The Ceiling() and Floor() methods are related.

You can round with custom numeric formatting as well.

Note that Decimal.Round() uses a different method than Math.Round();

Here is a useful post on the banker's rounding algorithm. See one of Raymond's humorous posts here about rounding...

Foredecker