Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Round 100.11 to 100.15 and 100.16 to 100.20 in c#

Tags:

c#

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"
like image 986
Jatinder Sharma Avatar asked Jan 20 '14 06:01

Jatinder Sharma


1 Answers

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).

like image 85
alzaimar Avatar answered Sep 28 '22 18:09

alzaimar