user1527762 user1527762 - 2 months ago 19
C# Question

Custom Rounding decimal numbers c#

I am looking to do custom rounding decimal numbers like the following

100.0000 => 100.0
226.4223 => 226.43
115.9080 => 115.91


Both input and output should be decimal numbers.

I have tried using Math.round but that does not give me the desired results.

For example:
Math.Round(226.4226, 2)
results in 226.42

Any idea?

Answer

Try something like this:

static decimal Round(decimal v)
{
    return Math.Ceiling(v * 100) / 100;
}

Usage:

decimal a = 100.00000M, b = 226.4223M, c = 115.9080M;

Console.WriteLine(Round(a).ToString("#.0#"));
Console.WriteLine(Round(b).ToString("#.0#"));
Console.WriteLine(Round(c).ToString("#.0#"));

Exercise for the reader: make this method round to any desired number of decimal places after the point (now it is always 2 places after the point).

Comments