How to round a number in .NET

There will be times when you need to round a number in .NET, if you don't know how to do it, you've come to the right place. The easiest way is to simply use Math.Round as below.

    decimal dValue = 9.35464363M;
    Console.WriteLine(Math.Round(dValue));

The above code will round the number to the nearest whole number but if you need to round to say 2dp., its easy.

    decimal dValue = 9.35564363M;
    Console.WriteLine(Math.Round(dValue, 2).ToString());

When the number after the decimal value is a 5 which in the above case, as it is in the example, the number is rounded down. You can force the rounding up by adding another parameter. In the below example, the output will be 9.35, without the MidpointRounding, the value will 3.44

    decimal dValue = 9.345M;
    Console.WriteLine(Math.Round(dValue, 2, MidpointRounding.AwayFromZero).ToString());

The default parameter of the Math.Round command is MidpointRounding.ToEven which is essentially rounding down rather than up so when the number after the decimal is a 5 then its treated as a 4 and rounded down. An 8 or 6 will result in the number being rounded up.

You can't cut corner by Import or using Math or System.Math, you have to qualify Round with Math every time. In .NET 4.7.2, doing "using System.Math;" will result in compiler error.

    error CS0246: The type or namespace name 'Math' could not be found (are you missing a using directive or an assembly reference?)

Tags - .NET

Last Modified : June 2023


About... / Contact.. / Cookie...