0

This is my code:

    decimal test1 = 190.5m;
    decimal test2 = 191.5m;
    var testResult1 = Math.Round(test1, 0); // =190 It should be 191!!!!
    var testResult2 = Math.Round(test2, 0); // =192 Correct.

Is there a way I could get the correct result? Maybe another library instead of System.Math?

  • 3
    You should describe behavior in edge cases, `var testResult1 = Math.Round(test1, 0, MidpointRounding.AwayFromZero);` – Dmitry Bychenko Sep 23 '22 at 10:47
  • 1
    Check the [docs for that method](https://learn.microsoft.com/en-us/dotnet/api/system.math.round?view=net-6.0#system-math-round(system-decimal-system-int32))... "This method uses the default rounding convention of `MidpointRounding.ToEven`." – phuzi Sep 23 '22 at 10:47
  • *"Check the docs for that method..."* is not something we should ever have to say. You should read the relevant documentation first, as a matter of course. – John Sep 23 '22 at 10:53

1 Answers1

0

This is by design. Albeit not what we have grown up with.

Find how you manage to round the way you expect here: https://learn.microsoft.com/en-us/dotnet/api/system.midpointrounding?redirectedfrom=MSDN&view=net-6.0

For a bit more reading and background, have a browse through some of the answers here: Why does .NET use banker's rounding as default?

chromebookdev
  • 305
  • 2
  • 11