Formatting -0.0 as 0.0

Bastiaan Veelo Bastiaan at Veelo.net
Fri Oct 15 12:37:44 UTC 2021


`std.format` maintains the minus sign when formatting a negative 
zero floating point value ([by 
design](https://forum.dlang.org/post/drkiaf$259l$1@digitaldaemon.com)):
```d
double r = -0.0;
writeln(r.format!"%#4.3f"); // -0.000
```

I am looking for a low-impact way to output negative zero as 
positive zero to prevent our users from raising their eyebrows.

There is a trick that would be somewhat acceptable if it worked 
consistently:
```d
double r = -0.0;
writeln((r + 0).format!"%#4.3f"); // 0.000
```
However, we have found that in some places with some ldc options 
the `+0` gets optimized out! I have not reduced the format used 
above where this happens, but here is another comparable example:
```d
// ldc options: -ffast-math -enable-inlining
import std;

void main()
{
     double r = -0.0;
     writeln(__LINE__, ":\t", r.format!"% 4.3f"); // -0.000
     writeln(__LINE__, ":\t", (r + 0).format!"% 4.3f"); // 0.000
     writeln(__LINE__, ":\t", r.posZero.format!"% 4.3f"); // 
-0.000 SURPRISE!
}

T posZero(T)(T value) if (isFloatingPoint!T)
{
     return value + 0;
}
```
https://run.dlang.io/is/XmAhLM

The alternative to `(r+0)` that does work consistently is 
`(r){return r == -0.0 ? 0.0 : r;}(r)` but that's just too much 
noise, and so the best I can come up with is inserting a call to
```d
T posZero(T)(T value) if (isFloatingPoint!T)
{
     return value == -0.0 ? 0.0 : value;
}
```

What I would like best is if there were a format specifier flag 
that does this conversion automatically, like "%> 4.3f". Does it 
make sense to add this? Is there a better way?

-- Bastiaan.


More information about the Digitalmars-d mailing list