Sean Kearon
Sean Kearon

Reputation: 11427

Rounding differences between decimal and double when formatting with ToString()

I am seeing differences in the result when formatting numeric values using ToString("F2").

0.125m.ToString("F2", CultureInfo.InvariantCulture); // 0.13
0.125.ToString("F2", CultureInfo.InvariantCulture); // 0.12

Why are these values rounded differently?

.NET Fiddle version of the code here.

Upvotes: 4

Views: 740

Answers (1)

Tim Schmelter
Tim Schmelter

Reputation: 460058

It's documented here:

When precision specifier controls the number of fractional digits in the result string, the result string reflects a number that is rounded to a representable result nearest to the infinitely precise result. If there are two equally near representable results:

  • On the .NET Framework and .NET Core up to .NET Core 2.0, the runtime selects the result with the greater least significant digit (that is, using MidpointRounding.AwayFromZero).
  • On .NET Core 2.1 and later, the runtime selects the result with an even least significant digit (that is, using MidpointRounding.ToEven).

Note that double is a floating binary point type. They are represented in binary system (like 11010.00110). When double is presented in decimal system it is only an approximation as not all binary numbers have exact representation in decimal system.

Upvotes: 4

Related Questions