Search code examples
c#rounding.net-standard-2.1

Round decimal number to positive infinity in c# in Net Standard library


I am trying to round up decimal numbers towards positive infinity in C# .Net Standard 2.1 library using Math.Round() function with MidpointRounding.ToPositiveInfinity enum as its mode parameter but I don't know why it doesn't exist in the MidpointRounding enum. the same enum value (ToPositiveInfinity) exists when the project is using .net 5. Code

Math.Round(2.336, 2, MidpointRounding.ToPositiveInfinity);

Does anyone know how I can fix this?

enter image description here


Solution

  • The MidpointRounding enum in .NET Standard 2.1 only has AwayFromZero and ToEven. The other modes, such as ToPositiveInfinity, were added later, in .NET Core 3.0. You can't use functionality which doesn't exist (in the runtime you're targetting), unless you implement it yourself.

    However, ToPositiveInfinity does the same thing as Math.Ceiling, so you can use that. Math.Ceiling however doesn't support specifying the number of decimal places to round to, but you can overcome that with a little multiplication:

    Math.Ceiling(2.336 * 100) / 100;