user1527762 - 1 year ago 90

C# Question

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

Any idea?

Answer Source

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