Beefy Boxes and Bandwidth Generously Provided by pair Networks
We don't bite newbies here... much
 
PerlMonks  

Re: Negative zero? There's gotta be a sprintf that undoes that, right?

by gamache (Friar)
on Dec 11, 2007 at 17:12 UTC ( [id://656433] : note . print w/replies, xml ) Need Help??


in reply to Negative zero? There's gotta be a sprintf that undoes that, right?

I know of no way to do this within sprintf, but how about this:
sub remove_sign_on_zero { my $num_str = shift; if ($num_str =~ /^-([0\.]+)$/) { return " $1"; } else { return $num_str; } } my $num = remove_sign_on_zero( sprintf('%7.5f', $example) );
The sub can be written golfier, if you like:
sub remove_sign_on_zero { $_[0]=~/^-([0\.]+)$/ ? " $1" : $_[0] }

Replies are listed 'Best First'.
Re^2: Negative zero? There's gotta be a sprintf that undoes that, right?
by suaveant (Parson) on Dec 12, 2007 at 15:13 UTC
    Now... here's a really sick method that uses the regexp, but only to remove the leading - when needed. -0 == 0 but also -0 lt 0 so...
    $num=sprintf("%7.5f",$num); $num=~s/^-// if $num == 0 && $num lt 0;
    minimal regexp work and works for any precision.

    Update Caveat... only works in locales where "-" is lower than 0-9

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