Search code examples
c#roundingmath.round

Is there a C# function or overload to Math.Round that will allow abnormal rounding practices?


I have the need to round a number for pricing sort of strangely as follows:

the value of an incoming price will be 3 decimal places (ie. 10.333)

It is necessary to round the first decimal place up if any number past said first decimal place is greater than 0.

for example:

10.300 = 10.3,
10.301 = 10.4,
10.333 = 10.4

before I go creating a custom method to do this I was wondering if anyone was aware of an existing usage/overload of Math.Round() or other already existing package to get this desired result?


Solution

  • Math.Round has an overload that accepts a MidpointRounding enum value, which lets you specify the strategy for rounding.

    In your case, you always want to round up, which is called ToPositiveInfinity.

    Math.Round(yourValue, 1, System.MidpointRounding.ToPositiveInfinity)