SoftwareNerd
SoftwareNerd

Reputation: 1905

C#: Math Round() results different values for different decimals

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.

Upvotes: 2

Views: 680

Answers (1)

Pavel Anikhouski
Pavel Anikhouski

Reputation: 23298

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

Upvotes: 4

Related Questions