in reply to Re^3: Negative zero? There's gotta be a sprintf that undoes that, right?
in thread Negative zero? There's gotta be a sprintf that undoes that, right?

Well, something is to be said for approaching a problem from different points of view and uncovering new truths. So I'll give it a try.

The solution wasn't as smooth as I'd hope, apparently -0.0 == 0.

my $sign = ""; my $number = -0.000001; my $example = sprintf("%.5f", $number); #$example = $number; #uncomment this, to remove the initial rounding print "A. Started with : $example \n"; if ($example < 0) { $example = -$example; $sign = "-"; print "B. Less than zero: changed to $example \n"; } print "C. the number is $example \n"; if ($example == 0 ) { print "D1. the number ($example) is equal to zero, removing the si +gn.\n"; $example *= -1; #(couldn't hurt, it's zero) print "D2. the number ($example) is equal to zero, removing the si +gn.\n"; $sign = ''; } print "E. proceeding to sprint $example with sign $sign .\n"; $tret = sprintf("rounded float: %s%7.5f : unrounded %7.5f", $sign, $ex +ample, $number); print "$tret \n";
Output:
A. Started with : -0.00000 
C. the number is -0.00000 
D1. the number (-0.00000) is equal to zero, removing the sign.
D2. the number (0) is equal to zero, removing the sign.
E. proceeding to sprint 0 with sign  .
rounded float: 0.00000 : unrounded -0.00000 
  • Comment on Re^4: Negative zero? There's gotta be a sprintf that undoes that, right?
  • Download Code

Replies are listed 'Best First'.
Re^5: Negative zero? There's gotta be a sprintf that undoes that, right?
by roboticus (Chancellor) on Dec 11, 2007 at 20:22 UTC
    rgiskard:

    Clearly I was wrong. ;^)

    But I have another idea--and it's a bit shorter than the last one!

    $example = abs($example) if abs($example) < 0.00001;
    I hope this one is better than the last one...

    Unfortunately, I've gotta pick up my son from school, so this one too is untested. ;^(

    ...roboticus

Re^5: Negative zero? There's gotta be a sprintf that undoes that, right?
by suaveant (Parson) on Dec 12, 2007 at 14:14 UTC
    Ironically, "-0.0" == 0 BUT triggers true in an ||... using that, however you CAN do...
    $num = '-0.0000009'; $num = sprintf("%7.5f",$num); $num = $num == 0 ? '0.00000' : $num; print "$num\n";
    I was hoping || would work, cuz then you could do
    $num = sprintf("%7.5f",$num) || '0.00000';
    but alas, no. The following works...
    $num = sprintf("%7.5f",$num)+0 || '0.00000';
    but you lose all trailing zeros, which works if you only want to round, but not for formatting, so probably doesn't help.

                    - Ant
                    - Some of my best work - (1 2 3)