Round 100.11 to 100.15 and 100.16 to 100.20 in c#
I have tried all these things but none of these helps me.
Math.Round(100.11, 2,MidpointRounding.AwayFromZero); //gives 100.11
Math.Round(100.11, 2,MidpointRounding.ToEven);//gives 100.11
Math.Round((Decimal)100.11, 2)//gives 100.11
(100.11).ToString("N2"); //gives "100.11"
Math.Floor(100.11);// gives 100.0
(100.11).ToString("#.##");//gives "100.11"
Math.Truncate(100.11);// gives 100.0
Math.Ceiling(100.11);//gives 101.0
(100.11).ToString("F4");// gives "100.1100"
This should give the desired result
decimal Round (decimal value, decimal granularity)
{
return Math.Ceiling(value/granularity+0.5M)*granularity;
}
// myResult = Round(110.11,0.05);
// myResult = Round(110.16,0.05);
In general: Set the granularity to the decimal value of how you want the values to be rounded, e.g. 0.1
will round up to the nearest decimal. You may also apply odd values like 0.25
which will round to 0.25
, 0.50
, 0.75
and 1.0
.
Removing the +0.5M
will simply round to the nearest value (instead of rounding up).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With