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?
CodePudding user response:
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)
CodePudding user response:
Approach with Math.Ceiling()
decimal input = 10.300m;
decimal result = Math.Ceiling(input * 10m) / 10m;
https://dotnetfiddle.net/Vck4Oa
CodePudding user response:
double d = 10.300;
var result= Math.Ceiling((decimal)d * 10) / 10;