Is it possible to parse signed zero? I tried several approaches but no one gives the proper result:
float test1 = Convert.ToSingle(\"-0.0\");
float test2 = f
I think there is no way to force float.Parse
(or Convert.ToSingle
) to respect negative zero. It just works like this (ignores sign in this case). So you have to check that yourself, for example:
string target = "-0.0";
float result = float.Parse(target, CultureInfo.InvariantCulture);
if (result == 0f && target.TrimStart().StartsWith("-"))
result = -0f;
If we look at source code for coreclr, we'll see (skipping all irrelevant parts):
private static bool NumberBufferToDouble(ref NumberBuffer number, ref double value)
{
double d = NumberToDouble(ref number);
uint e = DoubleHelper.Exponent(d);
ulong m = DoubleHelper.Mantissa(d);
if (e == 0x7FF)
{
return false;
}
if (e == 0 && m == 0)
{
d = 0; // < relevant part
}
value = d;
return true;
}
As you see, if mantissa and exponent are both zero - value is explicitly assigned to 0
. So there is no way you can change that.
Full .NET implementation has NumberBufferToDouble
as InternalCall
(implemented in pure C\C++), but I assume it does something similar.