1

I am looking to round decimal, 0.1 to 0.4 round down and 0.5 to 0.9 round up tried these but for some reason if value is 4.5 it rounds to 4 and not 5 all other values work fine. 3.5=4.0 , 5.5=6.0 but 4.5 =4.0 expecting 5.0

Math.Round(value / 2)
Math.Round(Math.Round(value / 2),0, MidpointRounding.AwayFromZero)
pfx
  • 20,323
  • 43
  • 37
  • 57
H Patel
  • 21
  • 1
  • 2
    Possible duplicate of [Why does .NET use banker's rounding as default?](https://stackoverflow.com/questions/311696/why-does-net-use-bankers-rounding-as-default) – Steve Clanton Sep 12 '18 at 18:03
  • 2
    Any time a method isn't doing what you expect, first [read the documentation](https://learn.microsoft.com/en-us/dotnet/api/system.math.round?view=netframework-4.7.1#System_Math_Round_System_Double_). – Dour High Arch Sep 12 '18 at 18:16
  • You have left out the most important fact: **what is the type of `value`**? – Eric Lippert Sep 12 '18 at 18:30
  • Also, why on your second line are you rounding, and then rounding the already-rounded value? That doesn't make any sense. – Eric Lippert Sep 12 '18 at 18:31
  • Possible duplicate of [C# Math.Round Error?](https://stackoverflow.com/questions/6890085/c-sharp-math-round-error) – Brian Sep 12 '18 at 21:27

1 Answers1

5

Your first line is using the default type of rounding (known as banker's rounding). Your second line almost gets what you want, but you don't need to include two calls to Math.Round().

For what you're wanting, it should probably look like this:

Math.Round((value / 2), 0, MidpointRounding.AwayFromZero)
// e.g. 3.5 => 4, 4.5 => 5, 5.5 => 6, etc.

Read more about banker's rounding here, and read more about Math.Round() here.

SlimsGhost
  • 2,849
  • 1
  • 10
  • 16