I need a floating GPIO pin

The fact that you included the

digitalWrite(D1, 0);

at all, implies the possibility that it was at some time before, written HIGH. If it is HIGH and you set it as OUTPUT, you put the full supply voltage on the pin. Since it appears this is what you are attempting to avoid, you need to set it LOW (also disabling any INPUT_PULLUP) and do that before setting it to OUTPUT.

Once you know the pin is written as LOW - and unless anything might alter it - it is sufficient to use only pinMode to thereafter alternate between OUTPUT and INPUT and back again.