2

I am getting a different value when using Math.Round with different decimal points, can someone correct me where am I going wrong.

   double r = Math.Round(1.235, 2,MidpointRounding.AwayFromZero);
   double t = Math.Round(19.185, 2,MidpointRounding.AwayFromZero);

r results in 1.24 and whereas t results in 19.18, the expected result for t is 19.19.

Pavel Anikhouski
  • 21,776
  • 12
  • 51
  • 66
SoftwareNerd
  • 1,875
  • 8
  • 29
  • 58
  • 1
    Have a look at this [article](https://learn.microsoft.com/en-us/dotnet/api/system.math.round?view=netframework-4.8#rounding-and-precision) – Pavel Anikhouski Nov 22 '19 at 11:58
  • 2
    Use decimal for better precision – Eldar Nov 22 '19 at 12:17
  • 1
    Consider that the exact value of 1.235 as stored in binary floating point is 1.2350000000000000976996261670137755572795867919921875 and 19.185 is 19.184999999999998721023075631819665431976318359375 – Chris Dunaway Nov 22 '19 at 15:48

1 Answers1

4

Accroding to Math.Round, Notes to Callers section

Because of the loss of precision that can result from representing decimal values as floating-point numbers or performing arithmetic operations on floating-point values, in some cases the Round(Double, Int32, MidpointRounding) method may not appear to round midpoint values as specified by the mode parameter. This is illustrated in the following example, where 2.135 is rounded to 2.13 instead of 2.14.

This sounds like your exact case, due the loss of precision 19.185 is rounded to 19.18 instead of 19.19. You can display values using the G17 format specifier to see all significant digits of precision

Console.WriteLine(1.235.ToString("G17"));
Console.WriteLine(19.185.ToString("G17"));

The output will be something like that

1.2350000000000001

19.184999999999999

As possible workaround, you can use decimal values with better precision

var r = Math.Round(1.235m, 2, MidpointRounding.AwayFromZero);
var t = Math.Round(19.185m, 2, MidpointRounding.AwayFromZero);

The result will be expected

Pavel Anikhouski
  • 21,776
  • 12
  • 51
  • 66
  • Finally a really good explanation of what's happening underneath. Thank you! I was also wondering why C# and MSSQL rounded the same number differently. Appears to be that when I set my number to float (in c#) I got the same result as in SQL, but when I had decimal, there was difference in 0,01. – VPetrovic Jun 04 '23 at 14:08