Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET Core 3 returns -0 string when a near 0 negative number is rounded

Tags:

c#

.net

.net-core

So this odd behavior was caught during a unit test we were implementing.

In .NET Core 3.x, if a near 0 negative number is rounded and then converted to a string, the string will display "-0" instead of 0.

Framework and .NET Core 2.x don't exhibit this behavior.

double d = -.1;
Console.WriteLine(Math.Round(d,0));

.NET Core Fiddle

Framework Fiddle

Is this a new bug within Core, or some strange intended change?

like image 225
Tronald Avatar asked Jul 07 '20 04:07

Tronald


1 Answers

This was a breaking change in .NET Core 3.0, for consistency between languages and IEEE-754 compliance.

Quoting from Floating-Point Parsing and Formatting improvements in .NET Core 3.0:

ToString(), ToString("G"), and ToString("R") will now return the shortest roundtrippable string.

The emphasis in the above is on "roundtrippable". Before this change, the negative zero "-0" did not roundtrip correctly, which was fixed by the combination of Fixing up the Double/Single parsing code to be correct #20707 and Roundtrip string format for single/double doesn't roundtrip -0 #9883.

like image 172
dxiv Avatar answered Sep 28 '22 07:09

dxiv