Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse signed zero?

Tags:

c#

parsing

zero

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 = float.Parse("-0.0");
float test3;
float.TryParse("-0.0", out test3);

If I use the value directly initialized it is just fine:

float test4 = -0.0f;

So the problem seems to be in the parsing procedures of c#. I hope somebody could tell if there is some option or workaround for that.

The difference could only be seen by converting to binary:

var bin= BitConverter.GetBytes(test4);
like image 890
mortal Avatar asked Apr 16 '18 08:04

mortal


1 Answers

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.

like image 64
Evk Avatar answered Sep 30 '22 20:09

Evk