Friday 7 October 2011

Rounding decimal or floating point numbers in C#

Example from stackoverflow: http://stackoverflow.com/questions/257005/how-do-you-round-a-number-to-two-decimal-places-in-c


decimal a = 1.994444M;

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

decimal b = 1.995555M;

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


Math.Round also has an overload for rounding-to-even:

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

No comments:

Post a Comment