Reputation: 11427
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
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:
MidpointRounding.AwayFromZero
).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