I have encountered this issue in my .NET Framework 4.8 project, but it also can be reproduced in .NET 8 (https://learn.microsoft.com/en-us/dotnet/api/system.math.round?view=net-8.0#code-try-2).
// incorrect rounding (double)
Console.WriteLine(Math.Round(71.335, 2, MidpointRounding.AwayFromZero)); // 71.33 (must to be 71.34)
Console.WriteLine(Math.Round(72.335, 2, MidpointRounding.AwayFromZero)); // 72.33 (must to be 72.34)
Console.WriteLine(Math.Round(73.335, 2, MidpointRounding.AwayFromZero)); // 73.33 (must to be 73.34)
// correct rounding (double)
Console.WriteLine(Math.Round(60.335, 2, MidpointRounding.AwayFromZero)); // 60.34
Console.WriteLine(Math.Round(83.335, 2, MidpointRounding.AwayFromZero)); // 83.34
// correct rounding (decimal) which was incorrect for double
Console.WriteLine(Math.Round(71.335M, 2, MidpointRounding.AwayFromZero)); // 71.34
Console.WriteLine(Math.Round(72.335M, 2, MidpointRounding.AwayFromZero)); // 72.34
Console.WriteLine(Math.Round(73.335M, 2, MidpointRounding.AwayFromZero)); // 73.34
I don’t understand what is the difference between 71.335
, 72.335
, etc. and 60.335
, 83.335
, etc. which makes Math.Round()
behave differently.
New contributor
Nikita Ivanov is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.