More Rounding Considerations in C#
[C#, .NET]
In a prior post, “NET 11 Release Candidate - Breaking Change - Numeric Conversion Rounding”, we looked at a potentially breaking issue with rounding before type conversions.
Which made me curious.
There are several ways to represent a float as a decimal.
- Using Convert.ToDecimal directly with the value
- Using Convert.ToDecimal with a variable of
floattype - Casting the value directly
- Casting a variable of
floattype
Here is the code we want to test:
var pi = 3.14f;
Console.WriteLine(Convert.ToDecimal(3.14));
Console.WriteLine(Convert.ToDecimal(3.14f));
Console.WriteLine(Convert.ToDecimal("3.14"));
Console.WriteLine($"{(decimal)3.14}");
Console.WriteLine($"{(decimal)3.14f}");
Console.WriteLine($"{(decimal)pi}");
To mix things up, we are including a double and a string representation.
If we run this under .NET 10, the results are as follows:

If we run the same code under .NET 11, the results are as follows:

A couple of things of interest:
- The .NET 11 change seems to affect all approximate types -
float,double Stringrepresentations are preserved as-is.- The approximation is not done when casting values
TLDR
If your code is doing any conversions using Convert or casting, you might want to prepare unit tests to ensure you have no surprises when you upgrade.
Happy hacking!