Well, it took a while for my subconscious to come up with the most trivial solution to this. Since "-0" gets interpretted as 0 and negative zero gives the string "-0", the following should work:
my $nz= -0.0; printf "%f\n", $nz; # Will print "-0.00000" on some platforms printf "%f\n", "$nz"; # Should give "0.00000"
But grabbing a quick platform to test showed this output:
-0.000000 -0.000000
So adding a slight pinch of voodoo gave me a solution that worked on the system that I tested it on, 0+"$nz":
#!/usr/bin/perl -w use strict; my $nz= -0.0; printf "%f\n", $nz; # May give -0.00000 printf "%f\n", "$nz"; # May give -0.00000, surprisingly printf "%f\n", 0+"$nz"; # Doesn't give -0.00000! __END__ -0.000000 -0.000000 0.000000
Go figure.
It is rather twisted that printf "%f", "-0" gives negative zero while printf "%f", -0 gives just zero (while eval "-0" and 0+"-0" all also just give zero). I'd be interested in more details on why that is so, but not enough to go source diving at the moment.
Update: Also note that you may not want to do $x= 0+"$x";, as that will slightly change the value of $x, perhaps increasing the accumulated error in this result (if $x is the result of some calculations). On the other hand, doing that can also have advantages in some situations. For example, if working with monetary values represented as dollars (or any other "cent"-based currency), then $x= 0+"$x" every so often is likely to remove accumulated error (well, reduce the accumulated error as much as is possible). The string representation of "14.28" is a more accurate representation of "14 dollars and 28 cents" than the floating-point value 14.28. So be careful.
Update: Oops, I should have read the specification more carefully. I thought the "problem" was negative zero, not negative numbers being displayed as negative zero (which was clearly indicated in the original node). Mea culpa.
- tye
In reply to Re: Negative zero? There's gotta be a sprintf that undoes that, right? (0+"$x")
by tye
in thread Negative zero? There's gotta be a sprintf that undoes that, right?
by rgiskard
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |