## Rounding off to nearest in C#

Posted by codingsense on February 4, 2010

Hi,

Here I am posting a simple post but its very useful and I saw lot of questions arising on the same. So made a sample to share with you.

There are 2 types of rounding off in the following sample

1) Rounding off to nearest 10, 100, 1000 and other multiples of 10

2) Rounding off to nearest decimal place

**Rounding off to nearest 10, 100, 1000 and other multiples of 10**

public static double RoundToNearest(double Amount, double RoundTo) { double ExcessAmount = Amount % RoundTo; if (ExcessAmount < (RoundTo / 2)) { Amount -= ExcessAmount; } else { Amount += (RoundTo - ExcessAmount); } return Amount; }

**Rounding off to nearest decimal place**

public static decimal RoundToNearestDecimal(decimal Amount, int DigitsToRound) { return Math.Round(Amount, DigitsToRound, MidpointRounding.AwayFromZero); }

Sample usage of the above code

Console.WriteLine("Amount = 123456789"); Console.WriteLine(RoundToNearest(12345678, 10)); Console.WriteLine(RoundToNearest(12345678, 100)); Console.WriteLine(RoundToNearest(12345678, 1000)); Console.WriteLine(RoundToNearest(12345678, 10000)); Console.WriteLine(RoundToNearest(12345678, 100000)); Console.WriteLine(); decimal deci = Convert.ToDecimal(123.456789); Console.WriteLine("Amount = 123.456789"); Console.WriteLine(RoundToNearestDecimal(deci, 1)); Console.WriteLine(RoundToNearestDecimal(deci, 2)); Console.WriteLine(RoundToNearestDecimal(deci, 3)); Console.WriteLine(RoundToNearestDecimal(deci, 4)); Console.WriteLine(RoundToNearestDecimal(deci, 5));

Sample output for the above code

Happy Learning

Codingsense 🙂

Advertisements

## mahesh said

Hi, This looks like a good foundation to start. But I have an issue where I cannot leave out the excess amount.

My Scenario: 4 columns namely Parent portfolio , Child Portfolio, Parent % and Child %. Use the values 14001, 8989, 0.72, 0.28 under these columns respectively

Parent PF * Parent % = A

Child * child % = B

Round A to the nearest 1000 (upper value)

Round B to the nearest 1000 (Bottom Value)

For Ex: if A is 7200 then round it to 8000.

if B is 2800 then round it to 2000. (Here percentage is taken as 72% and 28% ie .72 and 0.28 respectively.

## codingsense said

Hi,

Hi I feel that 7200 should become 7000 and 2800 should become 3000. Still if you insist the requirement is fine then please use the below method. I have reversed all the logics of the above method 🙂

public static double RoundToNearest(double Amount, double RoundTo)

{

double ExcessAmount = RoundTo – ( Amount % RoundTo);

if (ExcessAmount >= (RoundTo / 2))

{

Amount += ExcessAmount;

}

else

{

Amount -= (RoundTo – ExcessAmount);

}

return Amount;

}

Thanks,

Codingsense

## martinoss said

Hi you could also do this to round off (to thousands in this example):

Math.Round(Math.Truncate(9999M / 1000) * 1000); // = 9000

## asd said

Thank u

Helped a lot and its working